package cn.lili.modules.wallet.serviceimpl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.lili.common.enums.DictCodeEnum;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.properties.RocketmqCustomProperties;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.common.utils.SnowFlake;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.utils.SysDictUtils;
import cn.lili.modules.member.entity.dos.Extension;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.dos.Partner;
import cn.lili.modules.member.mapper.PartnerMapper;
import cn.lili.modules.member.service.*;
import cn.lili.modules.order.aftersale.entity.vo.AfterSaleVO;
import cn.lili.modules.order.aftersale.service.AfterSaleService;
import cn.lili.modules.order.order.entity.dos.Order;
import cn.lili.modules.order.order.entity.enums.OrderTypeEnum;
import cn.lili.modules.order.order.service.OrderService;
import cn.lili.modules.payment.entity.dos.CombinedPayment;
import cn.lili.modules.payment.service.CombinedPaymentService;
import cn.lili.modules.permission.service.StoreUserService;
import cn.lili.modules.system.entity.dos.Setting;
import cn.lili.modules.system.entity.dto.WithdrawalSetting;
import cn.lili.modules.system.entity.enums.SettingEnum;
import cn.lili.modules.system.service.SettingService;
import cn.lili.modules.transfer.entity.Transfer;
import cn.lili.modules.transfer.service.TransferService;
import cn.lili.modules.wallet.entity.dos.*;
import cn.lili.modules.wallet.entity.dto.CommissionData;
import cn.lili.modules.wallet.entity.dto.MemberWalletDTO;
import cn.lili.modules.wallet.entity.dto.MemberWalletUpdateDTO;
import cn.lili.modules.wallet.entity.dto.MemberWithdrawalMessage;
import cn.lili.modules.wallet.entity.enums.DepositServiceTypeEnum;
import cn.lili.modules.wallet.entity.enums.MemberWithdrawalDestinationEnum;
import cn.lili.modules.wallet.entity.enums.WalletOwnerEnum;
import cn.lili.modules.wallet.entity.enums.WithdrawStatusEnum;
import cn.lili.modules.wallet.entity.vo.MemberWalletSearchParams;
import cn.lili.modules.wallet.entity.vo.MemberWalletVO;
import cn.lili.modules.wallet.mapper.MemberWalletMapper;
import cn.lili.modules.wallet.service.*;
import cn.lili.modules.whitebar.service.RateSettingService;
import cn.lili.mybatis.util.PageUtil;
import cn.lili.rocketmq.RocketmqSendCallbackBuilder;
import cn.lili.rocketmq.tags.MemberTagsEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 会员余额业务层实现
 *
 * @author pikachu
 * @since 2020-02-25 14:10:16
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class MemberWalletServiceImpl extends ServiceImpl<MemberWalletMapper, MemberWallet>
		implements
			MemberWalletService {

	@Autowired
	private RocketMQTemplate rocketMQTemplate;

	@Autowired
	private RocketmqCustomProperties rocketmqCustomProperties;

	@Autowired
	private WalletDetailService walletDetailService;

	@Autowired
	private WalletFrozenDetailService walletFrozenDetailService;
	/**
	 * 预存款日志
	 */
	@Autowired
	private WalletLogService walletLogService;
	/**
	 * 设置
	 */
	@Autowired
	private SettingService settingService;
	/**
	 * 会员
	 */
	@Autowired
	private MemberService memberService;
	/**
	 * 会员提现申请
	 */
	@Autowired
	private MemberWithdrawApplyService memberWithdrawApplyService;
	// 提现费率
	@Autowired
	private RateSettingService rateSettingService;

	@Autowired
	private WalletLogDetailService walletLogDetailService;

	@Autowired
	private PartnerService partnerService;

	@Autowired
	private OrderService orderService;

	@Autowired
	private MemberWalletService memberWalletService;

	@Autowired
	private PartnerMapper partnerMapper;

	@Autowired
	private CombinedPaymentService combinedPaymentService;

	@Autowired
	private RechargeFowService rechargeFowService;
	@Autowired
	private StoreUserService storeUserService;

	@Autowired
	private AfterSaleService afterSaleService;

	@Autowired
	private TransferService transferService;

	@Override
	public MemberWalletVO getMemberWallet(String memberId, String owner) {
		// 构建查询条件
		QueryWrapper<MemberWallet> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("member_id", memberId);
		queryWrapper.eq("owner", owner);
		// 执行查询
		MemberWallet memberWallet = this.baseMapper.selectOne(queryWrapper);
		// 如果没有钱包，则创建钱包
		// if (!ObjectUtil.isAllNotEmpty(memberWallet)) {
		if (memberWallet == null && StringUtils.isNotEmpty(memberId)) {
			memberWallet = this.save(memberId, memberService.getById(memberId).getUsername(), owner);
		}
		// 返回查询数据
		return new MemberWalletVO(memberWallet.getMemberWallet(), memberWallet.getMemberFrozenWallet());
	}

	@Override
	public List<MemberWallet> getMemberWalletById(String memberId) {
		QueryWrapper<MemberWallet> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("member_id", memberId);
		return this.baseMapper.selectList(queryWrapper);
	}

	// 城市合伙人与平台分佣费率
	public Double apportionFee(String text) {
		return Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.APPORTION_FEE.dictCode(), text));
	}

	/**
	 * 扣钱逻辑
	 *
	 * @param memberWalletUpdateDTO
	 *            变动模型
	 * @param walletLogDetail
	 * @return
	 */
	@Override
	public Boolean increaseWithdrawal(MemberWalletUpdateDTO memberWalletUpdateDTO, WalletLogDetail walletLogDetail) {
		// 检测会员预存款讯息是否存在，如果不存在则新建
		MemberWallet memberWallet = this.checkMemberWallet(memberWalletUpdateDTO.getMemberId(),
				memberWalletUpdateDTO.getOwner());
		// 余额变动
		Double before = memberWallet.getMemberWallet();
		Double after = CurrencyUtil.add(memberWallet.getMemberWallet(), memberWalletUpdateDTO.getMoney());
		memberWallet.setMemberWallet(after == null ? 0D : after);
		memberWallet.setMemberFrozenWallet(
				CurrencyUtil.sub(memberWallet.getMemberFrozenWallet(), memberWalletUpdateDTO.getMoney()));
		this.updateById(memberWallet);
		// 新增预存款日志
		WalletLog walletLog = new WalletLog(memberWallet.getMemberName(), memberWalletUpdateDTO, before, after);
		walletLogService.save(walletLog);

		if (walletLogDetail != null && walletLogDetail.getMoney() != null) {
			walletLogDetail.setLogId(walletLog.getId());
			walletLogDetailService.save(walletLogDetail);
		}
		return true;
	}

	/**
	 * 加钱逻辑
	 *
	 * @param memberWalletUpdateDTO
	 *            变动模型
	 * @param walletLogDetail
	 * @return
	 */
	@Override
	public Boolean increase(MemberWalletUpdateDTO memberWalletUpdateDTO, WalletLogDetail walletLogDetail) {
		log.info("开始-- increase {}",
				JSONUtil.toJsonStr(memberWalletUpdateDTO) + "--" + JSONUtil.toJsonStr(walletLogDetail));
		// 检测会员预存款讯息是否存在，如果不存在则新建
		MemberWallet memberWallet = this.checkMemberWallet(memberWalletUpdateDTO.getMemberId(),
				memberWalletUpdateDTO.getOwner());
		log.info("MemberWallet {}", JSONUtil.toJsonStr(memberWallet));
		// 新增预存款
		Double before = memberWallet.getMemberWallet();
		Double after = CurrencyUtil.add(memberWallet.getMemberWallet(), memberWalletUpdateDTO.getMoney());
		memberWallet.setMemberWallet(after == null ? 0D : after);
		log.info("updateById memberWallet {}", JSONUtil.toJsonStr(memberWallet));
		this.baseMapper.updateById(memberWallet);
		// 新增预存款日志
		WalletLog walletLog = new WalletLog(memberWallet.getMemberName(), memberWalletUpdateDTO, before, after);
		log.info("save walletLog {}", JSONUtil.toJsonStr(walletLog));
		walletLogService.save(walletLog);

		if (walletLogDetail != null && walletLogDetail.getMoney() != null) {
			walletLogDetail.setLogId(walletLog.getId());
			walletLogDetailService.save(walletLogDetail);
			log.info("save walletLogDetail {}", JSONUtil.toJsonStr(walletLogDetail));
		}
		return true;
	}

	@Override
	public Boolean inFrozen(MemberWalletUpdateDTO memberWalletUpdateDTO) {
		// 检测会员预存款讯息是否存在，如果不存在则新建
		MemberWallet memberWallet = this.checkMemberWallet(memberWalletUpdateDTO.getMemberId(),
				memberWalletUpdateDTO.getOwner());
		// 新增冻结款
		Double before = memberWallet.getMemberFrozenWallet();
		Double after = CurrencyUtil.add(memberWallet.getMemberFrozenWallet(), memberWalletUpdateDTO.getMoney());
		memberWallet.setMemberFrozenWallet(after);
		this.baseMapper.updateById(memberWallet);
		// 新增预存款日志
		WalletLog walletLog = new WalletLog(memberWallet.getMemberName(), memberWalletUpdateDTO, before, after);
		walletLogService.save(walletLog);
		return true;
	}

	@Override
	public Boolean reduce(MemberWalletUpdateDTO memberWalletUpdateDTO, WalletLogDetail walletLogDetail) {
		// 检测会员预存款讯息是否存在，如果不存在则新建
		MemberWallet memberWallet = this.checkMemberWallet(memberWalletUpdateDTO.getMemberId(),
				memberWalletUpdateDTO.getOwner());
		// 减少预存款，需要校验 如果不够扣减预存款
		if (0 > CurrencyUtil.sub(memberWallet.getMemberWallet(), memberWalletUpdateDTO.getMoney())) {
			return false;
		}
		Double before = memberWallet.getMemberWallet();
		Double after = CurrencyUtil.sub(memberWallet.getMemberWallet(), memberWalletUpdateDTO.getMoney());
		memberWallet.setMemberWallet(after == null ? 0D : after);
		// 保存记录
		this.updateById(memberWallet);
		// 新增预存款日志
		WalletLog walletLog = new WalletLog(memberWallet.getMemberName(), memberWalletUpdateDTO, true, before, after);
		walletLogService.save(walletLog);
		if (walletLogDetail != null && walletLogDetail.getMoney() != null) {
			walletLogDetail.setLogId(walletLog.getId());
			walletLogDetailService.save(walletLogDetail);
		}
		return true;
	}

	@Override
	public Boolean reduceWithdrawal(MemberWalletUpdateDTO memberWalletUpdateDTO, WalletLogDetail walletLogDetail) {
		// 检测会员预存款讯息是否存在，如果不存在则新建
		MemberWallet memberWallet = this.checkMemberWallet(memberWalletUpdateDTO.getMemberId(),
				memberWalletUpdateDTO.getOwner());
		// 减少预存款，需要校验 如果不够扣减预存款
		if (0 > CurrencyUtil.sub(memberWallet.getMemberWallet(), memberWalletUpdateDTO.getMoney())) {
			throw new ServiceException(ResultCode.WALLET_WITHDRAWAL_INSUFFICIENT);
		}
		Double before = memberWallet.getMemberWallet();
		Double after = CurrencyUtil.sub(memberWallet.getMemberWallet(), memberWalletUpdateDTO.getMoney());
		memberWallet.setMemberWallet(after == null ? 0D : after);
		memberWallet.setMemberFrozenWallet(
				CurrencyUtil.add(memberWallet.getMemberFrozenWallet(), memberWalletUpdateDTO.getMoney()));
		// 修改余额
		this.updateById(memberWallet);
		// 新增预存款日志
		WalletLog walletLog = new WalletLog(memberWallet.getMemberName(), memberWalletUpdateDTO, true, before, after);
		walletLogService.save(walletLog);
		if (walletLogDetail != null && walletLogDetail.getMoney() != null) {
			walletLogDetail.setLogId(walletLog.getId());
			walletLogDetailService.save(walletLogDetail);
		}
		return true;

	}

	@Override
	public Boolean reduceFrozen(MemberWalletUpdateDTO memberWalletUpdateDTO) {
		// 检测会员预存款讯息是否存在，如果不存在则新建
		MemberWallet memberWallet = this.checkMemberWallet(memberWalletUpdateDTO.getMemberId(),
				memberWalletUpdateDTO.getOwner());
		// 校验此金额是否超过冻结金额
		if (0 > CurrencyUtil.sub(memberWallet.getMemberFrozenWallet(), memberWalletUpdateDTO.getMoney())) {
			throw new ServiceException(ResultCode.WALLET_WITHDRAWAL_INSUFFICIENT);
		}
		Double before = memberWallet.getMemberFrozenWallet();
		Double after = CurrencyUtil.sub(memberWallet.getMemberFrozenWallet(), memberWalletUpdateDTO.getMoney());
		memberWallet.setMemberFrozenWallet(after);
		this.updateById(memberWallet);
		// 新增预存款日志
		WalletLog walletLog = new WalletLog(memberWallet.getMemberName(), memberWalletUpdateDTO, true, before, after);
		walletLogService.save(walletLog);
		return true;
	}

	/**
	 * 检测会员预存款是否存在，如果不存在则新建
	 *
	 * @param memberId
	 *            会员id
	 */
	private MemberWallet checkMemberWallet(String memberId, String owner) {
		// 获取会员预存款信息
		MemberWallet memberWallet = this
				.getOne(new QueryWrapper<MemberWallet>().eq("member_id", memberId).eq("owner", owner));
		// 如果会员预存款信息不存在则同步重新建立预存款信息
		if (memberWallet == null && StringUtils.isNotEmpty(memberId)) {
			Member member = memberService.getById(memberId);
			if (member != null) {
				memberWallet = this.save(memberId, member.getUsername(), owner);
			} else {
				throw new ServiceException(ResultCode.USER_AUTHORITY_ERROR);
			}
		}
		return memberWallet;
	}

	@Override
	public void setMemberWalletPassword(Member member, String password) {
		// 对密码进行加密
		String pwd = new BCryptPasswordEncoder().encode(password);
		// 校验会员预存款是否存在
		QueryWrapper<MemberWallet> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("member_id", member.getId());
		MemberWallet memberWallet = this.getOne(queryWrapper);
		// 如果 预存款信息不为空 执行设置密码
		if (memberWallet != null) {
			memberWallet.setWalletPassword(pwd);
			this.updateById(memberWallet);
		}
	}

	@Override
	public Boolean checkPassword() {
		// 获取当前登录会员
		AuthUser authUser = UserContext.getCurrentUser();
		// 构建查询条件
		QueryWrapper<MemberWallet> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("member_id", authUser.getId());
		MemberWallet wallet = this.getOne(queryWrapper);
		return wallet != null && !StringUtils.isEmpty(wallet.getWalletPassword());
	}

	@Override
	public MemberWallet save(String memberId, String memberName, String owner) {
		// 获取会员预存款信息
		MemberWallet memberWallet = this
				.getOne(new QueryWrapper<MemberWallet>().eq("member_id", memberId).eq("owner", owner));
		if (memberWallet != null) {
			return memberWallet;
		}
		memberWallet = new MemberWallet();
		memberWallet.setMemberId(memberId);
		memberWallet.setMemberName(memberName);
		memberWallet.setMemberWallet(0D);
		memberWallet.setMemberFrozenWallet(0D);
		memberWallet.setOwner(owner);
		this.save(memberWallet);
		return memberWallet;
	}

	/**
	 * 提现方法 1、先执行平台逻辑，平台逻辑成功后扣减第三方余额，顺序问题为了防止第三方提现成功，平台逻辑失败导致第三方零钱已提现，而我们商城余额未扣减
	 * 2、如果余额扣减失败 则抛出异常，事务回滚
	 *
	 * @param price
	 *            提现金额
	 * @return
	 */
	@Override
	public MemberWithdrawApply applyWithdrawal(Double price, String owner, String cardId) {
		MemberWithdrawalMessage memberWithdrawalMessage = new MemberWithdrawalMessage();
		AuthUser authUser = UserContext.getCurrentUser();
		// 构建审核参数
		MemberWithdrawApply memberWithdrawApply = new MemberWithdrawApply();
		memberWithdrawApply.setMemberId(authUser.getId());
		memberWithdrawApply.setMemberName(authUser.getNickName());
		memberWithdrawApply.setApplyPrice(price);
		memberWithdrawApply.setOwner(owner);
		memberWithdrawApply.setCardId(cardId);
		String remark = "";
		// 计算实际到账金额和手续费
		String member = memberService.findByPartner(authUser.getId());
		String dictText = member;
		String value = "";
		try {
			switch (owner) {
				case "PROMOTE_HY" : {
					remark = "推广钱包";
					value = SysDictUtils.getValueString(DictCodeEnum.PROMOTE_WITHDRAWAL_RATE.dictCode(), dictText);
					break;
				}
				case "PROMOTE_FW" : {
					remark = "推广钱包";
					value = SysDictUtils.getValueString(DictCodeEnum.PROMOTE_WITHDRAWAL_RATE.dictCode(), dictText);
					break;
				}
				case "PROMOTE" : {
					remark = "推广钱包";
					value = SysDictUtils.getValueString(DictCodeEnum.PROMOTE_WITHDRAWAL_RATE.dictCode(), dictText);
					break;
				}
				case "SALE" : {
					remark = "销售钱包";
					value = SysDictUtils.getValueString(DictCodeEnum.SALE_WITHDRAWAL_RATE.dictCode(), dictText);
					break;
				}
				default :
					break;
			}
			if (StringUtils.isEmpty(value)) {
				throw new ServiceException(ResultCode.DICT_LI_NAME_NO_EXIST);
			}
		} catch (Exception e) {
			throw new ServiceException(ResultCode.DICT_LI_NAME_NO_EXIST);
		}

		Double realMoney = CurrencyUtil.mul(Double.parseDouble(value), price);
		memberWithdrawApply.setApplyMoney(realMoney);
		memberWithdrawApply.setHandlingMoney(CurrencyUtil.sub(price, realMoney));
		memberWithdrawApply.setFee(Double.parseDouble(value));
		memberWithdrawalMessage.setRealMoney(realMoney);
		memberWithdrawalMessage.setHandlingMoney(CurrencyUtil.sub(price, realMoney));
		memberWithdrawApply.setApplyStatus(WithdrawStatusEnum.APPLY.name());
		String sn = "W" + SnowFlake.getId();
		memberWithdrawApply.setSn(sn);
		memberWithdrawalMessage.setStatus(WithdrawStatusEnum.APPLY.name());
		MemberWallet from = getMemberWalletInfo(authUser.getId(), owner);
		MemberWallet admin = getMemberWalletInfo("admin", WalletOwnerEnum.RECHARGE.name(), "平台");// 平台消费钱包

		memberWithdrawApply.setBeforeMoney(from.getMemberWallet());
		withdrawApply(sn, from, admin, price, remark + "余额提现申请");

		// 推广钱包-会员费 提现
		if (owner.equals(WalletOwnerEnum.PROMOTE_HY.name())) {
			Map<String, Object> stringObjectMap = rechargeFowService.updatePromote(sn, price, authUser.getId(), "21");
			memberWithdrawApply.setApplyPrice(Double.valueOf(stringObjectMap.get("alreadyPrice").toString()));// 申请提现焕呗额
			memberWithdrawApply.setApplyMoney(Double.parseDouble(stringObjectMap.get("alreadyMoney").toString()));// 申请提现现金额
			memberWithdrawApply.setFee(Double.parseDouble(stringObjectMap.get("fee").toString()));// 提现费率
			memberWithdrawApply.setHandlingMoney(Double.parseDouble(stringObjectMap.get("colPrice").toString()));// 手续费
			memberWithdrawApply.setWithholdingAdvance(
					withholdingAdvance(Double.parseDouble(stringObjectMap.get("alreadyMoney").toString())));// 预扣预缴税额
		}
		// 销售 提现
		if (owner.equals(WalletOwnerEnum.SALE.name())) {
			Map<String, Object> stringObjectMap = memberWithdrawApplyService.txList(price, sn, authUser.getId(), "11");
			memberWithdrawApply.setApplyPrice(Double.valueOf(stringObjectMap.get("alreadyPrice").toString()));// 申请提现焕呗额
			memberWithdrawApply.setApplyMoney(Double.parseDouble(stringObjectMap.get("alreadyMoney").toString()));// 申请提现现金额
			memberWithdrawApply.setFee(Double.parseDouble(stringObjectMap.get("fee").toString()));// 提现费率
			memberWithdrawApply.setHandlingMoney(Double.parseDouble(stringObjectMap.get("colPrice").toString()));// 手续费
		}
		// 发送余额提现申请消息
		memberWithdrawalMessage.setMemberId(authUser.getId());
		memberWithdrawalMessage.setPrice(price);
		memberWithdrawalMessage.setDestination(MemberWithdrawalDestinationEnum.WECHAT.name());
		String destination = rocketmqCustomProperties.getMemberTopic() + ":" + MemberTagsEnum.MEMBER_WITHDRAWAL.name();
		rocketMQTemplate.asyncSend(destination, memberWithdrawalMessage, RocketmqSendCallbackBuilder.commonCallback());
		memberWithdrawApplyService.save(memberWithdrawApply);
		return memberWithdrawApply;
	}

	@Override
	public Double withholdingAdvance(Double money) {
		Double advance = 0D;
		Setting setting = settingService.get(SettingEnum.WITHDRAWAL_SETTING.toString());
		WithdrawalSetting withdrawalSetting = JSONUtil.toBean(setting.getSettingValue(), WithdrawalSetting.class);
		if (money.compareTo(withdrawalSetting.getTax3()) <= 0
				&& money.compareTo(withdrawalSetting.getDeduction4()) > 0) {
			// 4000以内
			advance = CurrencyUtil
					.sub(CurrencyUtil.mul(CurrencyUtil.sub(money, withdrawalSetting.getDeduction4()), 0.2D), 0D);// (money
																													// -
																													// d4)
																													// *
																													// 20%
																													// -0
		} else if (money.compareTo(withdrawalSetting.getTax1()) <= 0
				&& money.compareTo(withdrawalSetting.getTax3()) > 0) {
			// 4000-20000
			advance = CurrencyUtil.sub(CurrencyUtil.mul(CurrencyUtil.mul(money, CurrencyUtil.sub(1D, 0.2D)), 0.2D),
					withdrawalSetting.getDeduction1());// money * (1 - 20%) * 20% -d1
		} else if (money.compareTo(withdrawalSetting.getTax1()) > 0
				&& money.compareTo(withdrawalSetting.getTax2()) < 0) {
			// 20000-50000
			advance = CurrencyUtil.sub(CurrencyUtil.mul(CurrencyUtil.mul(money, CurrencyUtil.sub(1D, 0.2D)), 0.3D),
					withdrawalSetting.getDeduction2());// money * (1 - 20%) * 30% -d2
		} else if (money.compareTo(withdrawalSetting.getTax2()) >= 0) {
			// 50000以上
			advance = CurrencyUtil.sub(CurrencyUtil.mul(CurrencyUtil.mul(money, CurrencyUtil.sub(1D, 0.2D)), 0.4D),
					withdrawalSetting.getDeduction3());// money * (1 - 20%) * 40% -d3
		}
		return advance;
	}

	@Override
	public Boolean withdrawal(MemberWithdrawApply memberWithdrawApply) {
		memberWithdrawApply.setInspectTime(new Date());
		// 保存或者修改零钱提现
		this.memberWithdrawApplyService.saveOrUpdate(memberWithdrawApply);
		// TODO 调用自动提现接口
		boolean result = true;
		// 如果微信提现失败 则抛出异常 回滚数据
		if (!result) {
			throw new ServiceException(ResultCode.WALLET_ERROR_INSUFFICIENT);
		}
		return result;
	}

	@Override
	public IPage<MemberWalletDTO> findMemberWalletDTO(MemberWalletSearchParams memberWalletSearchParams) {
		return this.baseMapper.findMemberWalletDTO(PageUtil.initPage(memberWalletSearchParams),
				memberWalletSearchParams.queryWrapper());
	}

	@Override
	public IPage<MemberWalletDTO> findMemberWalletDTOStore(MemberWalletSearchParams memberWalletSearchParams) {
		return this.baseMapper.findMemberWalletDTOStore(PageUtil.initPage(memberWalletSearchParams),
				memberWalletSearchParams.queryWrapper());
	}

	@Override
	public IPage<MemberWalletDTO> findCommissionVOStore(MemberWalletSearchParams memberWalletSearchParams) {
		return this.baseMapper.findCommissionVOStore(PageUtil.initPage(memberWalletSearchParams),
				memberWalletSearchParams.queryWrapper());
	}

	@Override
	public Boolean updateFrozenWallet(String memberId, Double flowPrice, String owner) {
		return this.getBaseMapper().updateFrozenWallet(memberId, flowPrice, owner) > 0;
	}

	/**
	 * 充值逻辑
	 *
	 * @param recharge
	 */
	@Override
	public void updateWallet(Recharge recharge) {
		MemberWallet to = getMemberWalletInfo(recharge.getMemberId(), recharge.getOwner(), recharge.getMemberName());
		walletUpdate(recharge.getRechargeSn(), DepositServiceTypeEnum.WALLET_DEPARTMENT.name(), null, to, recharge.getYiBei(), "会员余额充值，充值单号为：" + recharge.getRechargeSn());// 交易金额
	}
	// 分佣逻辑

	/**
	 * 授信
	 *
	 * @param sn
	 *            订单号
	 * @param from
	 *            转出钱包
	 * @param to
	 *            转入钱包
	 * @param money
	 *
	 * @return
	 */
	@Transactional
	public boolean departmentOrder(String sn, MemberWallet from, MemberWallet to, Double money) {
		MemberWallet admin = getMemberWalletInfo("admin", WalletOwnerEnum.RECHARGE.name(), "平台");// 平台消费钱包
		walletUpdate(sn, DepositServiceTypeEnum.WALLET_DEPARTMENT.name(), admin, to, money, "授信拨款");// 交易金额
		return true;
	}

	/**
	 * 还款
	 *
	 * @param sn
	 *            订单号
	 * @param from
	 *            转出钱包
	 * @param to
	 *            转入钱包
	 * @param money
	 *            交易金额
	 * @return
	 */
	@Transactional
	public boolean repayOrder(String sn, MemberWallet from, MemberWallet to, Double money) {
		MemberWallet admin = getMemberWalletInfo("admin", WalletOwnerEnum.RECHARGE.name(), "平台");// 平台消费钱包
		walletUpdate(sn, DepositServiceTypeEnum.WALLET_REPAY.name(), from, admin, money, "授信还款");// 交易金额
		return true;
	}

	/**
	 * 提现
	 *
	 * @param sn
	 *            订单号
	 * @param from
	 *            转出钱包
	 * @param to
	 *            转入钱包
	 * @param money
	 *            交易金额
	 * @return
	 */
	@Transactional
	public boolean withdrawApply(String sn, MemberWallet from, MemberWallet to, Double money, String remark) {
		walletUpdate(sn, DepositServiceTypeEnum.WALLET_WITHDRAWAL.name(), from, to, money, remark);// 交易金额
		return true;
	}

	/**
	 * 提现退回
	 *
	 * @param sn
	 *            订单号
	 * @param from
	 *            转出钱包
	 * @param to
	 *            转入钱包
	 * @param money
	 *            交易金额
	 * @return
	 */
	@Transactional
	public boolean withdrawApplyRefund(String sn, MemberWallet from, MemberWallet to, Double money, String remark) {
		walletUpdate(sn, DepositServiceTypeEnum.WALLET_WITHDRAWALREFUND.name(), from, to, money, remark);// 交易金额
		return true;
	}

	/**
	 * @param sn
	 *            订单号
	 * @param from
	 *            转出钱包
	 * @param to
	 *            转入钱包
	 * @param money
	 *            交易金额
	 * @param colMoney
	 *            运费
	 * @param comMoney
	 *            手续费
	 * @return
	 */
	@Transactional
	public boolean payOrder(String sn, MemberWallet from, MemberWallet to, Double money, Double colMoney,
			Double comMoney) {
		MemberWallet admin = getMemberWalletInfo("admin", WalletOwnerEnum.SALE.name(), "平台");// 平台消费钱包
		walletUpdate(sn, DepositServiceTypeEnum.WALLET_PAY.name(), from, admin, money, "订单付款");// 交易金额
		if (colMoney > 0D) {
			walletUpdate(sn, DepositServiceTypeEnum.WALLET_COLLECT.name(), from, admin, colMoney, "订单运费");// 运费
		}

		Order order = orderService.getOrderBySn(sn);
		if (comMoney > 0D) {
			MemberWallet adminp = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(), "平台");// 手续费 ，平台推广钱包

			String proxyUser = getProxy(from.getMemberId());
			if (ObjectUtil.isNotNull(proxyUser)) {
				MemberWallet proxy = memberWalletService.getMemberWalletInfo(proxyUser,
						WalletOwnerEnum.PROMOTE_FW.name());// 代理商
				// 虚拟订单不冻结佣金
				if (!OrderTypeEnum.VIRTUAL.name().equals(order.getOrderType())) {
					walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from, proxy,
							CurrencyUtil.mul(comMoney, apportionFee("城市合伙人")), "订单手续费");// 手续费到代理商
					walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from, adminp,
							CurrencyUtil.mul(comMoney, apportionFee("平台")), "订单手续费");// 手续费到平台
				} else {
					walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from, proxy,
							CurrencyUtil.mul(comMoney, apportionFee("城市合伙人")), "订单手续费");// 手续费到代理商
					walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from, adminp,
							CurrencyUtil.mul(comMoney, apportionFee("平台")), "订单手续费");// 手续费到平台
				}
			} else {
				if (!OrderTypeEnum.VIRTUAL.name().equals(order.getOrderType())) {
					walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from, adminp, comMoney,
							"订单手续费");// 手续费
				} else {
					walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from, adminp, comMoney,
							"订单手续费");// 手续费
				}
			}
		}
		splitCommissionFrozen(sn, from, to, money, comMoney, "xf");// 消费分佣
		return true;
	}

	/**
	 * @param sn
	 *            订单号
	 * @param owner
	 *            转出钱包类型
	 * @param memberId
	 *            转出人
	 * @param to
	 *            转入钱包
	 * @param money
	 *            交易金额
	 * @param colMoney
	 *            运费
	 * @return
	 */
	@Transactional
	public boolean combinedPayOrder(String sn, String owner, String memberId, MemberWallet to, Double money,
			Double colMoney) {

		List<String> ownerList = Arrays.asList(owner.split(","));
		Order order = orderService.getOrderBySn(sn);
		if (CollectionUtils.isNotEmpty(ownerList)) {
			MemberWallet admin = getMemberWalletInfo("admin", WalletOwnerEnum.SALE.name(), "平台");// 平台消费钱包
			MemberWallet from = memberWalletService.getMemberWalletInfo(memberId, ownerList.get(0));

			Double comMoneyAll = 0D;// 总手续费
			Double price = money;// 交易金额剩余
			Double colLast = colMoney;// 运费剩余
			for (int i = 0; i < ownerList.size(); i++) {
				if (i == 0) {
					// 第一个默认为推广钱包
					MemberWallet from1 = memberWalletService.getMemberWalletInfo(memberId, ownerList.get(i));

					// 计算手续费
					Double fee = CurrencyUtil
							.add(Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.ORDER_FEE.dictCode())), 1D);// 手续费费率
					Double memberWallet = memberWalletService.getMemberWallet(memberId, ownerList.get(i))
							.getMemberWallet();// 钱包余额
					Double jiaoyi = 0D;
					Double shouxufei = 0D;
					Double yunfei = 0D;
					if (price >= memberWallet) {
						// 交易金额大于钱包余额，扣除所有金额
						jiaoyi = CurrencyUtil.div(memberWallet, fee);// 交易金额
						shouxufei = CurrencyUtil.sub(memberWallet, jiaoyi);// 手续费
						price = CurrencyUtil.sub(price, jiaoyi);
					} else {
						// 交易金额小于钱包余额
						Double jine = CurrencyUtil.div(memberWallet, fee);// 交易金额
						if (price <= jine) {
							// 够扣手续费和交易金额
							jiaoyi = price;
							shouxufei = CurrencyUtil.mul(CurrencyUtil.sub(fee, 1D), jiaoyi);// 手续费
							price = 0D;
							// 钱包余额
							memberWallet = CurrencyUtil.sub(memberWallet, shouxufei, jiaoyi);

							// 扣完商品之后扣运费
							if (colLast > 0D) {
								if (colLast <= memberWallet) {
									yunfei = colLast;
									walletUpdate(sn, DepositServiceTypeEnum.WALLET_COLLECT.name(), from1, admin, yunfei,
											"订单运费");// 运费
									colLast = 0D;
								} else {
									yunfei = memberWallet;
									walletUpdate(sn, DepositServiceTypeEnum.WALLET_COLLECT.name(), from1, admin, yunfei,
											"订单运费");// 运费
									colLast = CurrencyUtil.sub(colLast, yunfei);
								}
							}
						} else {
							// 不够扣手续费
							jiaoyi = jine;
							price = CurrencyUtil.sub(price, jiaoyi);
							shouxufei = CurrencyUtil.sub(memberWallet, jiaoyi);// 手续费
						}
					}

					MemberWallet adminp = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(), "平台");// 手续费
																												// ，平台推广钱包
					walletUpdate(sn, DepositServiceTypeEnum.WALLET_PAY.name(), from1, admin, jiaoyi, "订单付款");// 交易金额

					if (shouxufei > 0D) {
						String proxyUser = getProxy(from1.getMemberId());
						if (StringUtils.isNotEmpty(proxyUser)) {
							MemberWallet proxy = memberWalletService.getMemberWalletInfo(proxyUser,
									WalletOwnerEnum.PROMOTE_FW.name());// 代理商
							// 虚拟订单不冻结佣金
							if (!OrderTypeEnum.VIRTUAL.name().equals(order.getOrderType())) {
								walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from1, proxy,
										CurrencyUtil.mul(shouxufei, apportionFee("城市合伙人")), "订单手续费");// 手续费到代理商
								walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from1, adminp,
										CurrencyUtil.mul(shouxufei, apportionFee("平台")), "订单手续费");// 手续费到平台
							} else {
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from1, proxy,
										CurrencyUtil.mul(shouxufei, apportionFee("城市合伙人")), "订单手续费");// 手续费到代理商
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from1, adminp,
										CurrencyUtil.mul(shouxufei, apportionFee("平台")), "订单手续费");// 手续费到平台
							}
						} else {
							// 虚拟订单不冻结佣金
							if (!OrderTypeEnum.VIRTUAL.name().equals(order.getOrderType())) {
								walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from1, adminp,
										shouxufei, "订单手续费");// 手续费
							} else {
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from1, adminp,
										shouxufei, "订单手续费");// 手续费
							}
						}
					}

					updateCombined(sn, ownerList.get(i), from1, jiaoyi, shouxufei, yunfei);
					comMoneyAll = CurrencyUtil.add(comMoneyAll, shouxufei);
					// 推广钱包-会员费，支付扣款逻辑
					if (ownerList.get(i).equals(WalletOwnerEnum.PROMOTE_HY.name())) {
						rechargeFowService.updatePromote(sn, jiaoyi, from1.getMemberId(), "22");
						if (yunfei > 0D) {
							rechargeFowService.updatePromote(sn, yunfei, from1.getMemberId(), "23");
						}
						if (shouxufei > 0D) {
							rechargeFowService.updatePromote(sn, shouxufei, from1.getMemberId(), "24");
						}
					}
					if (ownerList.get(i).equals(WalletOwnerEnum.SALE.name())) {
						memberWithdrawApplyService.txList(price, sn, from1.getMemberId(), "12");
						if (yunfei > 0D) {
							memberWithdrawApplyService.txList(yunfei, sn, from1.getMemberId(), "13");
						}
						if (shouxufei > 0D) {
							memberWithdrawApplyService.txList(shouxufei, sn, from1.getMemberId(), "14");
						}
					}
				} else if (i == ownerList.size() - 1) {
					// 最后一个金额一定富裕，不能扣除所有金额
					MemberWallet from2 = memberWalletService.getMemberWalletInfo(memberId, ownerList.get(i));
					Double shouxufei = 0D;
					Double yunfei = 0D;
					// 计算手续费
					if (StrUtil.equalsAny(ownerList.get(i), WalletOwnerEnum.SALE.name(), WalletOwnerEnum.PROMOTE.name(),
							WalletOwnerEnum.PROMOTE_FW.name(), WalletOwnerEnum.PROMOTE_HY.name())) {
						// 交易金额小于钱包余额
						shouxufei = CurrencyUtil.mul(
								Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.ORDER_FEE.dictCode())), price);// 手续费
						comMoneyAll = CurrencyUtil.add(comMoneyAll, shouxufei);

						MemberWallet adminp = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(), "平台");// 手续费
																													// ，平台推广钱包

						if (shouxufei > 0D) {
							String proxyUser = getProxy(from2.getMemberId());
							if (StringUtils.isNotEmpty(proxyUser)) {
								MemberWallet proxy = memberWalletService.getMemberWalletInfo(proxyUser,
										WalletOwnerEnum.PROMOTE_FW.name());// 代理商
								// 虚拟订单不冻结佣金
								if (!OrderTypeEnum.VIRTUAL.name().equals(order.getOrderType())) {
									walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from2, proxy,
											CurrencyUtil.mul(shouxufei, apportionFee("城市合伙人")), "订单手续费");// 手续费到代理商
									walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from2,
											adminp, CurrencyUtil.mul(shouxufei, apportionFee("平台")), "订单手续费");// 手续费到平台
								} else {
									walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from2, proxy,
											CurrencyUtil.mul(shouxufei, apportionFee("城市合伙人")), "订单手续费");// 手续费到代理商
									walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from2, adminp,
											CurrencyUtil.mul(shouxufei, apportionFee("平台")), "订单手续费");// 手续费到平台
								}
							} else {
								// 虚拟订单不冻结佣金
								if (!OrderTypeEnum.VIRTUAL.name().equals(order.getOrderType())) {
									walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from2,
											adminp, shouxufei, "订单手续费");// 手续费
								} else {
									walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from2, adminp,
											shouxufei, "订单手续费");// 手续费
								}
							}
						}
					}
					// 扣运费
					if (colLast > 0D) {
						yunfei = colLast;
						walletUpdate(sn, DepositServiceTypeEnum.WALLET_COLLECT.name(), from2, admin, yunfei, "订单运费");// 运费
						colLast = 0D;
					}

					walletUpdate(sn, DepositServiceTypeEnum.WALLET_PAY.name(), from2, admin, price, "订单付款");// 交易金额
					updateCombined(sn, ownerList.get(i), from2, price, shouxufei, 0D);
					// 推广钱包-会员费，支付扣款逻辑
					if (ownerList.get(i).equals(WalletOwnerEnum.PROMOTE_HY.name())) {
						rechargeFowService.updatePromote(sn, price, from2.getMemberId(), "22");
						if (yunfei != 0D) {
							rechargeFowService.updatePromote(sn, yunfei, from2.getMemberId(), "23");
						}
						if (shouxufei > 0D) {
							rechargeFowService.updatePromote(sn, shouxufei, from2.getMemberId(), "24");
						}
					}
					if (ownerList.get(i).equals(WalletOwnerEnum.SALE.name())) {
						memberWithdrawApplyService.txList(price, sn, from2.getMemberId(), "12");
						if (yunfei != 0D) {
							memberWithdrawApplyService.txList(yunfei, sn, from2.getMemberId(), "13");
						}
						if (shouxufei > 0D) {
							memberWithdrawApplyService.txList(shouxufei, sn, from2.getMemberId(), "14");
						}
					}
					price = 0D;
				} else {
					// 扣除所有金额
					MemberWallet from3 = memberWalletService.getMemberWalletInfo(memberId, ownerList.get(i));
					Double memberWallet = memberWalletService.getMemberWallet(memberId, ownerList.get(i))
							.getMemberWallet();// 钱包余额
					Double jiaoyi = 0D;// 交易金额
					Double shouxufei = 0D;// 手续费
					Double yunfei = 0D;// 运费
					// 计算手续费
					if (StrUtil.equalsAny(ownerList.get(i), WalletOwnerEnum.SALE.name(), WalletOwnerEnum.PROMOTE.name(),
							WalletOwnerEnum.PROMOTE_FW.name(), WalletOwnerEnum.PROMOTE_HY.name())) {
						Double fee = CurrencyUtil.add(
								Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.ORDER_FEE.dictCode())), 1D);// 手续费费率

						if (price >= memberWallet) {
							// 交易金额大于钱包余额，扣除所有金额
							jiaoyi = CurrencyUtil.div(memberWallet, fee);// 交易金额
							shouxufei = CurrencyUtil.sub(memberWallet, jiaoyi);// 手续费
							price = CurrencyUtil.sub(price, jiaoyi);
						} else {
							// 交易金额小于钱包余额
							Double jine = CurrencyUtil.div(memberWallet, fee);// 交易金额
							if (price <= jine) {
								// 够扣手续费和交易金额
								jiaoyi = price;
								shouxufei = CurrencyUtil.mul(CurrencyUtil.sub(fee, 1D), jiaoyi);// 手续费
								price = 0D;
								// 钱包余额
								memberWallet = CurrencyUtil.sub(memberWallet, shouxufei, jiaoyi);

								// 扣完商品之后扣运费
								if (colLast > 0D) {
									if (colLast <= memberWallet) {
										yunfei = colLast;
										walletUpdate(sn, DepositServiceTypeEnum.WALLET_COLLECT.name(), from3, admin,
												yunfei, "订单运费");// 运费
										colLast = 0D;
									} else {
										yunfei = memberWallet;
										walletUpdate(sn, DepositServiceTypeEnum.WALLET_COLLECT.name(), from3, admin,
												yunfei, "订单运费");// 运费
										colLast = CurrencyUtil.sub(colLast, yunfei);
									}
								}
							} else {
								// 不够扣手续费
								jiaoyi = jine;
								price = CurrencyUtil.sub(price, jiaoyi);
								shouxufei = CurrencyUtil.sub(memberWallet, jiaoyi);// 手续费
							}
						}
						MemberWallet adminp = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(), "平台");// 手续费
																													// ，平台推广钱包

						if (shouxufei > 0D) {
							String proxyUser = getProxy(from3.getMemberId());
							if (StringUtils.isNotEmpty(proxyUser)) {
								MemberWallet proxy = memberWalletService.getMemberWalletInfo(proxyUser,
										WalletOwnerEnum.PROMOTE_FW.name());// 代理商
								// 虚拟订单不冻结佣金
								if (!OrderTypeEnum.VIRTUAL.name().equals(order.getOrderType())) {
									walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from3, proxy,
											CurrencyUtil.mul(shouxufei, apportionFee("城市合伙人")), "订单手续费");// 手续费到代理商
									walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from3,
											adminp, CurrencyUtil.mul(shouxufei, apportionFee("平台")), "订单手续费");// 手续费到平台
								} else {
									walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from3, proxy,
											CurrencyUtil.mul(shouxufei, apportionFee("城市合伙人")), "订单手续费");// 手续费到代理商
									walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from3, adminp,
											CurrencyUtil.mul(shouxufei, apportionFee("平台")), "订单手续费");// 手续费到平台
								}
							} else {
								// 虚拟订单不冻结佣金
								if (!OrderTypeEnum.VIRTUAL.name().equals(order.getOrderType())) {
									walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from3,
											adminp, shouxufei, "订单手续费");// 手续费
								} else {
									walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from3, adminp,
											shouxufei, "订单手续费");// 手续费
								}
							}
						}

						comMoneyAll = CurrencyUtil.add(comMoneyAll, shouxufei);
					} else {
						// 不需要手续费
						if (price >= memberWallet) {
							// 交易金额大于钱包余额，扣除所有金额
							jiaoyi = memberWallet;// 交易金额
							price = CurrencyUtil.sub(price, jiaoyi);
						} else {
							// 交易金额小于钱包余额
							if (price <= memberWallet) {
								// 够扣交易金额
								jiaoyi = price;
								price = 0D;
								// 钱包余额
								memberWallet = CurrencyUtil.sub(memberWallet, jiaoyi);

								// 扣完商品之后扣运费
								if (colLast > 0D) {
									if (colLast <= memberWallet) {
										yunfei = colLast;
										walletUpdate(sn, DepositServiceTypeEnum.WALLET_COLLECT.name(), from3, admin,
												yunfei, "订单运费");// 运费
										colLast = 0D;
									} else {
										yunfei = memberWallet;
										walletUpdate(sn, DepositServiceTypeEnum.WALLET_COLLECT.name(), from3, admin,
												yunfei, "订单运费");// 运费
										colLast = CurrencyUtil.sub(colLast, yunfei);
									}
								}
							}
						}
					}
					walletUpdate(sn, DepositServiceTypeEnum.WALLET_PAY.name(), from3, admin, jiaoyi, "订单付款");// 交易金额
					updateCombined(sn, ownerList.get(i), from3, jiaoyi, shouxufei, 0D);
					price = CurrencyUtil.sub(price, jiaoyi);
					// 推广钱包-会员费，支付扣款逻辑
					if (ownerList.get(i).equals(WalletOwnerEnum.PROMOTE_HY.name())) {
						rechargeFowService.updatePromote(sn, jiaoyi, from3.getMemberId(), "22");
						if (yunfei != 0D) {
							rechargeFowService.updatePromote(sn, yunfei, from3.getMemberId(), "23");
						}
						if (shouxufei > 0D) {
							rechargeFowService.updatePromote(sn, shouxufei, from3.getMemberId(), "24");
						}
					}
					if (ownerList.get(i).equals(WalletOwnerEnum.SALE.name())) {
						memberWithdrawApplyService.txList(jiaoyi, sn, from3.getMemberId(), "12");
						if (yunfei != 0D) {
							memberWithdrawApplyService.txList(yunfei, sn, from3.getMemberId(), "13");
						}
						if (shouxufei > 0D) {
							memberWithdrawApplyService.txList(shouxufei, sn, from3.getMemberId(), "14");
						}
					}
				}
			}
			order.setCommission(comMoneyAll);
			orderService.updateById(order);
			log.info("分佣冻结 splitCommissionFrozen---------------------------------------- start");
			CommissionData cd = new CommissionData(money, comMoneyAll);// 佣金计算
			// angelCommission(sn,from,to,money,comMoney,type,cd);//给天使分佣
			careerCommissionFrozen(sn, from, to, money, comMoneyAll, "xf", cd);// 给事业分佣
			// dealerCommission(sn,from,to,money,comMoneyAll,"xf",cd);//给代理商分佣
			log.info("分佣冻结 splitCommissionFrozen---------------------------------------- end");
		}

		return true;
	}

	/**
	 * 订单完成
	 *
	 * @param sn
	 *            订单号
	 * @param to
	 *            转入钱包
	 * @param money
	 *            交易金额
	 * @param colMoney
	 *            运费
	 * @return
	 */
	@Transactional
	public Boolean complateOrder(String sn, MemberWallet to, Double money, Double colMoney) {
		MemberWallet admin = getMemberWalletInfo("admin", WalletOwnerEnum.SALE.name(), "平台");
		walletUpdate(sn, DepositServiceTypeEnum.WALLET_PAY.name(), admin, to, money, "订单完成打款");// 平台 到B 交易金额
		if (colMoney > 0D) {
			walletUpdate(sn, DepositServiceTypeEnum.WALLET_COLLECT.name(), admin, to, colMoney, "订单完成运费打款");// 平台 到B 运费
		}
		return true;
	}

	/**
	 * 订单退款
	 *
	 * @param sn
	 * @param colFlag
	 *            包含运费， true 是，false 否
	 * @return
	 */
	@Transactional
	public Boolean cancelOrder(String sn, boolean colFlag, String afterSaleNo) {
		// 退订单金额和运费
		List<WalletDetail> datas = getWalletLogDetail(sn, colFlag);
		Order order = orderService.getBySn(sn);
		String proxyUser = getProxy(order.getMemberId());
		AfterSaleVO afterSale = afterSaleService.getAfterSale(afterSaleNo);
		if (ObjectUtil.isNotNull(datas)) {
			if (afterSale != null) {
				Double comMoney = 0D;
				if (!WalletOwnerEnum.RECHARGE.name().equals(order.getOwner())) {
					comMoney = CurrencyUtil.mul(afterSale.getActualRefundPrice(),
							Double.valueOf(SysDictUtils.getValueString("order_fee")), 5);
					afterSale.setCommissionPrice(comMoney);
					afterSaleService.updateById(afterSale);
				}
				for (WalletDetail item : datas) {
					MemberWallet from = getMemberWalletInfo(item.getPayee(), item.getPayeeOwner());// 之前收款方
					MemberWallet to = getMemberWalletInfo(item.getPayer(), item.getPayerOwner());// 之前的付款方
					Double money = afterSale.getActualRefundPrice();
					String transactionType = DepositServiceTypeEnum.WALLET_REFUND.name();
					if (item.getTransactionType().indexOf("WALLET_COMMISSION") != -1) {
						transactionType = item.getTransactionType() + "_REFUND";
						if (StringUtils.isNotEmpty(proxyUser)) {
							if (item.getTransactionType().equals(DepositServiceTypeEnum.WALLET_COMMISSION_FW.name())
									&& "admin".equals(item.getPayee())) {
								// 平台退还佣金
								money = CurrencyUtil.mul(comMoney, apportionFee("平台"));
							} else if (item.getTransactionType()
									.equals(DepositServiceTypeEnum.WALLET_COMMISSION_FW.name())
									&& !"admin".equals(item.getPayee())) {
								// 城市退还佣金
								money = CurrencyUtil.mul(comMoney, apportionFee("城市合伙人"));
							} else if (item.getTransactionType()
									.equals(DepositServiceTypeEnum.WALLET_COMMISSION_TS.name())
									&& "admin".equals(item.getPayer())) {
								// 天使退还平台佣金
								money = CurrencyUtil.mul(afterSale.getActualRefundPrice(), Double.valueOf(
										SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "天使合伙人")), 5);
								money = CurrencyUtil.mul(money, apportionFee("平台"));
							} else if (item.getTransactionType()
									.equals(DepositServiceTypeEnum.WALLET_COMMISSION_TS.name())
									&& !"admin".equals(item.getPayer())) {
								// 天使退还城市佣金
								money = CurrencyUtil.mul(afterSale.getActualRefundPrice(), Double.valueOf(
										SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "天使合伙人")), 5);
								money = CurrencyUtil.mul(money, apportionFee("城市合伙人"));
							} else if (item.getTransactionType()
									.equals(DepositServiceTypeEnum.WALLET_COMMISSION_SY.name())
									&& "admin".equals(item.getPayer())) {
								// 事业退还平台佣金
								money = CurrencyUtil.mul(afterSale.getActualRefundPrice(), Double.valueOf(
										SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "事业合伙人")), 5);
								money = CurrencyUtil.mul(money, apportionFee("平台"));
							} else if (item.getTransactionType()
									.equals(DepositServiceTypeEnum.WALLET_COMMISSION_SY.name())
									&& !"admin".equals(item.getPayer())) {
								// 事业退还城市佣金
								money = CurrencyUtil.mul(afterSale.getActualRefundPrice(), Double.valueOf(
										SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "事业合伙人")), 5);
								money = CurrencyUtil.mul(money, apportionFee("城市合伙人"));
							}
						} else {
							if (item.getTransactionType().equals(DepositServiceTypeEnum.WALLET_COMMISSION_FW.name())
									&& "admin".equals(item.getPayee())) {
								// 平台退还佣金
								money = comMoney;
							} else if (item.getTransactionType()
									.equals(DepositServiceTypeEnum.WALLET_COMMISSION_TS.name())
									&& "admin".equals(item.getPayer())) {
								// 天使退还平台佣金
								money = CurrencyUtil.mul(afterSale.getActualRefundPrice(), Double.valueOf(
										SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "天使合伙人")), 5);
							} else if (item.getTransactionType()
									.equals(DepositServiceTypeEnum.WALLET_COMMISSION_SY.name())
									&& "admin".equals(item.getPayer())) {
								// 事业退还平台佣金
								money = CurrencyUtil.mul(afterSale.getActualRefundPrice(), Double.valueOf(
										SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "事业合伙人")), 5);
							}
						}
						walletFrozenOut(sn, transactionType, from, to, money, "退款:" + item.getRemark());// 冻结佣金退款
						continue;
					} else if (item.getTransactionType().indexOf("WALLET_COLLECT") != -1) {
						transactionType = item.getTransactionType() + "_REFUND";
					}
					walletUpdate(sn, transactionType, from, to, money, "退款:" + item.getRemark());// 全部退款
				}
			} else {
				for (WalletDetail item : datas) {
					MemberWallet from = getMemberWalletInfo(item.getPayee(), item.getPayeeOwner());// 之前收款方
					MemberWallet to = getMemberWalletInfo(item.getPayer(), item.getPayerOwner());// 之前的付款方
					Double money = item.getMoney();
					String transactionType = DepositServiceTypeEnum.WALLET_REFUND.name();
					if (item.getTransactionType().indexOf("WALLET_COMMISSION") != -1) {
						transactionType = item.getTransactionType() + "_REFUND";
						walletFrozenOut(sn, transactionType, from, to, money, "退款:" + item.getRemark());// 冻结佣金退款
						continue;
					} else if (item.getTransactionType().indexOf("WALLET_COLLECT") != -1) {
						transactionType = item.getTransactionType() + "_REFUND";
					}
					walletUpdate(sn, transactionType, from, to, money, "退款:" + item.getRemark());// 全部退款
				}
			}

		}
		// 退冻结的佣金
		List<WalletFrozenDetail> walletFrozenDetail = getWalletFrozenDetail(sn);
		if (ObjectUtil.isNotNull(walletFrozenDetail)) {
			if (afterSale != null) {
				Double comMoney = 0D;
				if (!WalletOwnerEnum.RECHARGE.name().equals(order.getOwner())) {
					comMoney = CurrencyUtil.mul(afterSale.getActualRefundPrice(),
							Double.valueOf(SysDictUtils.getValueString("order_fee")), 5);
					afterSale.setCommissionPrice(comMoney);
					afterSaleService.updateById(afterSale);
				}
				for (WalletFrozenDetail item : walletFrozenDetail) {
					MemberWallet from = getMemberWalletInfo(item.getPayee(), item.getPayeeOwner());// 之前收款方
					MemberWallet to = getMemberWalletInfo(item.getPayer(), item.getPayerOwner());// 之前的付款方
					Double money = afterSale.getActualRefundPrice();
					String transactionType = DepositServiceTypeEnum.WALLET_REFUND.name();
					if (item.getTransactionType().indexOf("WALLET_COMMISSION") != -1) {
						transactionType = item.getTransactionType() + "_REFUND";
						if (StringUtils.isNotEmpty(proxyUser)) {
							if (item.getTransactionType().equals(DepositServiceTypeEnum.WALLET_COMMISSION_FW.name())
									&& "admin".equals(item.getPayee())) {
								// 平台退还佣金
								money = CurrencyUtil.mul(comMoney, apportionFee("平台"));
							} else if (item.getTransactionType()
									.equals(DepositServiceTypeEnum.WALLET_COMMISSION_FW.name())
									&& !"admin".equals(item.getPayee())) {
								// 城市退还佣金
								money = CurrencyUtil.mul(comMoney, apportionFee("城市合伙人"));
							} else if (item.getTransactionType()
									.equals(DepositServiceTypeEnum.WALLET_COMMISSION_TS.name())
									&& "admin".equals(item.getPayer())) {
								// 天使退还平台佣金
								money = CurrencyUtil.mul(afterSale.getActualRefundPrice(), Double.valueOf(
										SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "天使合伙人")), 5);
								money = CurrencyUtil.mul(money, apportionFee("平台"));
							} else if (item.getTransactionType()
									.equals(DepositServiceTypeEnum.WALLET_COMMISSION_TS.name())
									&& !"admin".equals(item.getPayer())) {
								// 天使退还城市佣金
								money = CurrencyUtil.mul(afterSale.getActualRefundPrice(), Double.valueOf(
										SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "天使合伙人")), 5);
								money = CurrencyUtil.mul(money, apportionFee("城市合伙人"));
							} else if (item.getTransactionType()
									.equals(DepositServiceTypeEnum.WALLET_COMMISSION_SY.name())
									&& "admin".equals(item.getPayer())) {
								// 事业退还平台佣金
								money = CurrencyUtil.mul(afterSale.getActualRefundPrice(), Double.valueOf(
										SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "事业合伙人")), 5);
								money = CurrencyUtil.mul(money, apportionFee("平台"));
							} else if (item.getTransactionType()
									.equals(DepositServiceTypeEnum.WALLET_COMMISSION_SY.name())
									&& !"admin".equals(item.getPayer())) {
								// 事业退还城市佣金
								money = CurrencyUtil.mul(afterSale.getActualRefundPrice(), Double.valueOf(
										SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "事业合伙人")), 5);
								money = CurrencyUtil.mul(money, apportionFee("城市合伙人"));
							}
						} else {
							if (item.getTransactionType().equals(DepositServiceTypeEnum.WALLET_COMMISSION_FW.name())
									&& "admin".equals(item.getPayee())) {
								// 平台退还佣金
								money = comMoney;
							} else if (item.getTransactionType()
									.equals(DepositServiceTypeEnum.WALLET_COMMISSION_TS.name())
									&& "admin".equals(item.getPayer())) {
								// 天使退还平台佣金
								money = CurrencyUtil.mul(afterSale.getActualRefundPrice(), Double.valueOf(
										SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "天使合伙人")), 5);
							} else if (item.getTransactionType()
									.equals(DepositServiceTypeEnum.WALLET_COMMISSION_SY.name())
									&& "admin".equals(item.getPayer())) {
								// 事业退还平台佣金
								money = CurrencyUtil.mul(afterSale.getActualRefundPrice(), Double.valueOf(
										SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "事业合伙人")), 5);
							}
						}
						walletFrozenOut(sn, transactionType, from, to, money, "退款:" + item.getRemark());// 冻结佣金退款
						continue;
					} else if (item.getTransactionType().indexOf("WALLET_COLLECT") != -1) {
						transactionType = item.getTransactionType() + "_REFUND";
					}
					walletUpdate(sn, transactionType, from, to, money, "退款:" + item.getRemark());// 全部退款
				}
			} else {
				for (WalletFrozenDetail item : walletFrozenDetail) {
					MemberWallet from = getMemberWalletInfo(item.getPayee(), item.getPayeeOwner());// 之前收款方
					MemberWallet to = getMemberWalletInfo(item.getPayer(), item.getPayerOwner());// 之前的付款方
					Double money = item.getMoney();
					String transactionType = DepositServiceTypeEnum.WALLET_REFUND.name();
					if (item.getTransactionType().indexOf("WALLET_COMMISSION") != -1) {
						transactionType = item.getTransactionType() + "_REFUND";
						walletFrozenOut(sn, transactionType, from, to, money, "退款:" + item.getRemark());// 冻结佣金退款
						continue;
					} else if (item.getTransactionType().indexOf("WALLET_COLLECT") != -1) {
						transactionType = item.getTransactionType() + "_REFUND";
					}
					walletUpdate(sn, transactionType, from, to, money, "退款:" + item.getRemark());// 全部退款
				}
			}

		}
		return true;
	}

	/**
	 * 订单支付佣金 冻结金额解冻到钱包，并保留原来的收付款关系 1.查出需要支付的佣金 = 付款-退款 已完成 2.（type增加确认类型'_confirm'）
	 * 已完成 3.冻结明细表增加确认明细 已完成 4.组装订单明细表，保留原有的付款方及付款时钱包动账前后数值 已完成
	 *
	 * @param sn
	 * @return
	 */
	@Transactional
	public Boolean confirmOrder(String sn) {
		List<WalletFrozenDetail> datas = getWalletFrozenDetail(sn);
		if (ObjectUtil.isNotNull(datas)) {
			for (WalletFrozenDetail item : datas) {
				MemberWallet to = getMemberWalletInfo(item.getPayee(), item.getPayeeOwner());// 收款方
				Double money = item.getMoney();
				String transactionType = item.getTransactionType();
				if (money != 0 && item.getTransactionType().indexOf("WALLET_COMMISSION") != -1) {
					transactionType = item.getTransactionType() + "_CONFIRM";
					WalletFrozenDetail walletFrozenDetail = walletFrozenOut(sn, transactionType, to, to, money,
							"佣金确认:" + item.getRemark());// 冻结佣金确认，给到收款方

					// 组装订单明细表，保留原有的付款方及付款时钱包动账前后数值
					WalletDetail detail = new WalletDetail();
					detail.setSn(sn);
					detail.setTransactionType(item.getTransactionType());
					detail.setPayer(item.getPayer());
					detail.setPayerName(item.getPayerName());
					detail.setPayerOwner(item.getPayerOwner());
					detail.setPayerBeforeMoney(item.getPayerBeforeMoney());
					detail.setPayerAfterMoney(item.getPayerAfterMoney());

					detail.setPayee(item.getPayee());
					detail.setPayeeName(item.getPayeeName());
					detail.setPayeeOwner(item.getPayeeOwner());
					detail.setPayeeBeforeMoney(walletFrozenDetail.getPayeeBeforeMoney());
					detail.setPayeeAfterMoney(walletFrozenDetail.getPayeeAfterMoney());

					detail.setMoney(money);
					detail.setRemark(item.getRemark());
					walletDetailService.save(detail);
					continue;
				}
			}

		}
		// 已经佣金确认，就不能再分佣了
		walletFrozenDetailService.updateBySn(sn);
		return true;
	}

	/**
	 * 扫码付款
	 *
	 * @param sn
	 * @param from
	 * @param to
	 * @param money
	 * @param comMoney
	 * @return
	 */
	@Transactional
	public boolean scanPay(String sn, MemberWallet from, MemberWallet to, Double money, Double comMoney) {
		walletUpdate(sn, DepositServiceTypeEnum.WALLET_PAY.name(), from, to, money, "扫码付款");// 转账

		MemberWallet admin = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(), "平台");

		if (comMoney > 0D) {
			String proxyUser = getProxy(from.getMemberId());
			if (StringUtils.isNotEmpty(proxyUser)) {
				MemberWallet proxy = memberWalletService.getMemberWalletInfo(proxyUser,
						WalletOwnerEnum.PROMOTE_FW.name());// 代理商
				walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from, proxy,
						CurrencyUtil.mul(comMoney, apportionFee("城市合伙人")), "扫码付款手续费");// 手续费到代理商
				walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from, admin,
						CurrencyUtil.mul(comMoney, apportionFee("平台")), "扫码付款手续费");// 手续费到平台
			} else {
				walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from, admin, comMoney, "扫码付款手续费");// 手续费
			}
		}

		splitCommission(sn, from, to, money, comMoney, "xf");// 转账分佣
		return true;
	}

	/**
	 * 转账
	 *
	 * @param sn
	 * @param from
	 * @param to
	 * @param money
	 * @param comMoney
	 * @return
	 */
	@Transactional
	public boolean transferPay(String sn, MemberWallet from, MemberWallet to, Double money, Double comMoney,
			String type) {
		if (type.equals("PORT_FEE")) {
			// 端口费
			walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW_REFUND.name(), from, to, money, "端口费");// 转账
		} else {
			walletUpdate(sn, DepositServiceTypeEnum.WALLET_PAY.name(), from, to, money, "转账");// 转账
		}

		MemberWallet admin = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(), "平台");

		if (comMoney > 0D) {
			String proxyUser = getProxy(from.getMemberId());
			if (StringUtils.isNotEmpty(proxyUser)) {
				MemberWallet proxy = memberWalletService.getMemberWalletInfo(proxyUser,
						WalletOwnerEnum.PROMOTE_FW.name());// 代理商
				walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from, proxy,
						CurrencyUtil.mul(comMoney, apportionFee("城市合伙人")), "转账手续费");// 手续费到代理商
				walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from, admin,
						CurrencyUtil.mul(comMoney, apportionFee("平台")), "转账手续费");// 手续费到平台
			} else {
				walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from, admin, comMoney, "转账手续费");// 手续费
			}
		}
		if (!type.equals("PORT_FEE")) {
			splitCommission(sn, from, to, money, comMoney, "xf");// 转账分佣
		}
		return true;
	}

	/**
	 * 转账 组合支付
	 *
	 * @param sn
	 *            订单号
	 * @param owner
	 *            转出钱包类型
	 * @param memberId
	 *            转出人
	 * @param to
	 *            转入钱包
	 * @param money
	 *            交易金额
	 * @return
	 */
	@Transactional
	public boolean combinedTransferPay(String sn, String owner, String memberId, MemberWallet to, Double money) {

		List<String> ownerList = Arrays.asList(owner.split(","));
		Transfer transfer = transferService.getTransferBySn(sn);

		if (CollectionUtils.isNotEmpty(ownerList)) {
			MemberWallet from = memberWalletService.getMemberWalletInfo(memberId, ownerList.get(0));

			Double comMoneyAll = 0D;// 总手续费
			Double price = money;// 交易金额剩余
			for (int i = 0; i < ownerList.size(); i++) {
				if (i == 0) {
					// 第一个默认为推广钱包，再计算手续费
					MemberWallet from1 = memberWalletService.getMemberWalletInfo(memberId, ownerList.get(i));
					// 扣除所有金额
					// 计算手续费
					Double fee = CurrencyUtil
							.add(Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.ORDER_FEE.dictCode())), 1D);// 手续费费率
					Double memberWallet = memberWalletService.getMemberWallet(memberId, ownerList.get(i))
							.getMemberWallet();// 钱包余额
					Double jiaoyi = CurrencyUtil.div(memberWallet, fee);// 交易金额
					Double shouxufei = CurrencyUtil.sub(memberWallet, jiaoyi);// 手续费

					MemberWallet adminp = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(), "平台");// 手续费
					walletUpdate(sn, DepositServiceTypeEnum.WALLET_PAY.name(), from1, to, jiaoyi, "转账");// 转账

					if (shouxufei > 0D) {
						String proxyUser = getProxy(from1.getMemberId());
						if (StringUtils.isNotEmpty(proxyUser)) {
							MemberWallet proxy = memberWalletService.getMemberWalletInfo(proxyUser,
									WalletOwnerEnum.PROMOTE_FW.name());// 代理商
							walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from1, proxy,
									CurrencyUtil.mul(shouxufei, apportionFee("城市合伙人")), "转账手续费");// 手续费到代理商
							walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from1, adminp,
									CurrencyUtil.mul(shouxufei, apportionFee("平台")), "转账手续费");// 手续费到平台
						} else {
							walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from1, adminp,
									shouxufei, "转账手续费");// 手续费
						}
					}
					updateCombined(sn, ownerList.get(i), from1, jiaoyi, shouxufei, 0D);

					// 推广钱包-会员费，支付扣款逻辑
					if (ownerList.get(i).equals(WalletOwnerEnum.PROMOTE_HY.name())) {
						rechargeFowService.updatePromote(sn, jiaoyi, from1.getMemberId(), "22");
						if (shouxufei > 0D) {
							rechargeFowService.updatePromote(sn, shouxufei, from1.getMemberId(), "24");
						}
					}
					// 支出转账金额
					if (ownerList.get(i).equals(WalletOwnerEnum.SALE.name())) {
						memberWithdrawApplyService.txList(money, sn, from1.getId(), "12");
						if (shouxufei > 0D) {
							memberWithdrawApplyService.txList(shouxufei, sn, from1.getId(), "14");
						}
					}

					price = CurrencyUtil.sub(price, jiaoyi);
					comMoneyAll = CurrencyUtil.add(comMoneyAll, shouxufei);
				} else if (i == ownerList.size() - 1) {
					// 最后一个金额一定富裕，不能扣除所有金额
					MemberWallet from2 = memberWalletService.getMemberWalletInfo(memberId, ownerList.get(i));
					Double shouxufei = 0D;// 手续费
					// 计算手续费
					if (StrUtil.equalsAny(ownerList.get(i), WalletOwnerEnum.SALE.name(), WalletOwnerEnum.PROMOTE.name(),
							WalletOwnerEnum.PROMOTE_FW.name(), WalletOwnerEnum.PROMOTE_HY.name())) {

						shouxufei = CurrencyUtil.mul(price,
								Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.ORDER_FEE.dictCode())));
						comMoneyAll = CurrencyUtil.add(comMoneyAll, shouxufei);

						MemberWallet adminp = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(), "平台");// 手续费

						if (shouxufei > 0D) {
							String proxyUser = getProxy(from2.getMemberId());
							if (StringUtils.isNotEmpty(proxyUser)) {
								MemberWallet proxy = memberWalletService.getMemberWalletInfo(proxyUser,
										WalletOwnerEnum.PROMOTE_FW.name());// 代理商
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from2, proxy,
										CurrencyUtil.mul(shouxufei, apportionFee("城市合伙人")), "转账手续费");// 手续费到代理商
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from2, adminp,
										CurrencyUtil.mul(shouxufei, apportionFee("平台")), "转账手续费");// 手续费到平台
							} else {
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from2, adminp,
										shouxufei, "转账手续费");// 手续费
							}
						}
					}
					walletUpdate(sn, DepositServiceTypeEnum.WALLET_PAY.name(), from2, to, price, "转账");// 转账
					updateCombined(sn, ownerList.get(i), from2, price, shouxufei, 0D);
					// 推广钱包-会员费，支付扣款逻辑
					if (ownerList.get(i).equals(WalletOwnerEnum.PROMOTE_HY.name())) {
						rechargeFowService.updatePromote(sn, price, from2.getMemberId(), "22");
						if (shouxufei > 0D) {
							rechargeFowService.updatePromote(sn, shouxufei, from2.getMemberId(), "24");
						}
					}
					// 支出销售金额
					if (ownerList.get(i).equals(WalletOwnerEnum.SALE.name())) {
						memberWithdrawApplyService.txList(money, sn, from2.getId(), "12");
						if (shouxufei > 0D) {
							memberWithdrawApplyService.txList(shouxufei, sn, from2.getId(), "14");
						}
					}
				} else {
					// 扣除所有金额
					MemberWallet from3 = memberWalletService.getMemberWalletInfo(memberId, ownerList.get(i));
					Double memberWallet = memberWalletService.getMemberWallet(memberId, ownerList.get(i))
							.getMemberWallet();// 钱包余额
					Double jiaoyi = memberWallet;// 交易金额
					Double shouxufei = 0D;// 手续费
					// 计算手续费
					if (StrUtil.equalsAny(ownerList.get(i), WalletOwnerEnum.SALE.name(), WalletOwnerEnum.PROMOTE.name(),
							WalletOwnerEnum.PROMOTE_FW.name(), WalletOwnerEnum.PROMOTE_HY.name())) {
						Double fee = CurrencyUtil.add(
								Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.ORDER_FEE.dictCode())), 1D);// 手续费费率
						jiaoyi = CurrencyUtil.div(memberWallet, fee);// 交易金额
						shouxufei = CurrencyUtil.sub(memberWallet, jiaoyi);// 手续费
						MemberWallet adminp = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(), "平台");// 手续费

						if (shouxufei > 0D) {
							String proxyUser = getProxy(from3.getMemberId());
							if (StringUtils.isNotEmpty(proxyUser)) {
								MemberWallet proxy = memberWalletService.getMemberWalletInfo(proxyUser,
										WalletOwnerEnum.PROMOTE_FW.name());// 代理商
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from3, proxy,
										CurrencyUtil.mul(shouxufei, apportionFee("城市合伙人")), "转账手续费");// 手续费到代理商
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from3, adminp,
										CurrencyUtil.mul(shouxufei, apportionFee("平台")), "转账手续费");// 手续费到平台
							} else {
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from3, adminp,
										shouxufei, "转账手续费");// 手续费
							}
						}
						comMoneyAll = CurrencyUtil.add(comMoneyAll, shouxufei);
					}
					walletUpdate(sn, DepositServiceTypeEnum.WALLET_PAY.name(), from3, to, jiaoyi, "转账");// 转账
					updateCombined(sn, ownerList.get(i), from3, jiaoyi, shouxufei, 0D);
					// 推广钱包-会员费，支付扣款逻辑
					if (ownerList.get(i).equals(WalletOwnerEnum.PROMOTE_HY.name())) {
						rechargeFowService.updatePromote(sn, jiaoyi, from3.getMemberId(), "22");
						if (shouxufei > 0D) {
							rechargeFowService.updatePromote(sn, shouxufei, from3.getMemberId(), "24");
						}
					}
					// 支出销售金额
					if (ownerList.get(i).equals(WalletOwnerEnum.SALE.name())) {
						memberWithdrawApplyService.txList(money, sn, from3.getId(), "12");
						if (shouxufei > 0D) {
							memberWithdrawApplyService.txList(shouxufei, sn, from3.getId(), "14");
						}
					}
					price = CurrencyUtil.sub(price, jiaoyi);
				}
			}
			transfer.setCommission(comMoneyAll);
			transfer.setTransferMoney(CurrencyUtil.add(transfer.getTransferMoney(), comMoneyAll));
			transferService.updateById(transfer);

		}

		return true;
	}

	/**
	 * 扫码付款 组合支付
	 *
	 * @param sn
	 *            订单号
	 * @param owner
	 *            转出钱包类型
	 * @param memberId
	 *            转出人
	 * @param to
	 *            转入钱包
	 * @param money
	 *            交易金额
	 * @return
	 */
	@Transactional
	public boolean combinedPay(String sn, String owner, String memberId, MemberWallet to, Double money) {

		List<String> ownerList = Arrays.asList(owner.split(","));
		Order order = orderService.getOrderBySn(sn);

		if (CollectionUtils.isNotEmpty(ownerList)) {
			MemberWallet from = memberWalletService.getMemberWalletInfo(memberId, ownerList.get(0));

			Double comMoneyAll = 0D;// 总手续费
			Double price = money;// 交易金额剩余
			for (int i = 0; i < ownerList.size(); i++) {
				if (i == 0) {
					// 第一个默认为推广钱包，扣除运费，再计算手续费
					MemberWallet from1 = memberWalletService.getMemberWalletInfo(memberId, ownerList.get(i));
					// 扣除所有金额
					// 计算手续费
					Double fee = CurrencyUtil
							.add(Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.ORDER_FEE.dictCode())), 1D);// 手续费费率
					Double memberWallet = memberWalletService.getMemberWallet(memberId, ownerList.get(i))
							.getMemberWallet();// 钱包余额
					Double jiaoyi = CurrencyUtil.div(memberWallet, fee);// 交易金额
					Double shouxufei = CurrencyUtil.sub(memberWallet, jiaoyi);// 手续费

					MemberWallet adminp = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(), "平台");// 手续费
																												// ，平台推广钱包
					walletUpdate(sn, DepositServiceTypeEnum.WALLET_PAY.name(), from1, to, jiaoyi, "扫码付款");// 转账

					if (shouxufei > 0D) {
						String proxyUser = getProxy(from1.getMemberId());
						if (StringUtils.isNotEmpty(proxyUser)) {
							MemberWallet proxy = memberWalletService.getMemberWalletInfo(proxyUser,
									WalletOwnerEnum.PROMOTE_FW.name());// 代理商
							walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from1, proxy,
									CurrencyUtil.mul(shouxufei, apportionFee("城市合伙人")), "扫码付款手续费");// 手续费到代理商
							walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from1, adminp,
									CurrencyUtil.mul(shouxufei, apportionFee("平台")), "扫码付款手续费");// 手续费到平台
						} else {
							walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from1, adminp,
									shouxufei, "扫码付款手续费");// 手续费
						}
					}
					updateCombined(sn, ownerList.get(i), from1, jiaoyi, shouxufei, 0D);

					// 推广钱包-会员费，支付扣款逻辑
					if (ownerList.get(i).equals(WalletOwnerEnum.PROMOTE_HY.name())) {
						rechargeFowService.updatePromote(sn, jiaoyi, from1.getMemberId(), "22");
						if (shouxufei > 0D) {
							rechargeFowService.updatePromote(sn, shouxufei, from1.getMemberId(), "24");
						}
					}
					// 支出销售金额
					if (ownerList.get(i).equals(WalletOwnerEnum.SALE.name())) {
						memberWithdrawApplyService.txList(money, sn, from1.getId(), "12");
						if (shouxufei > 0D) {
							memberWithdrawApplyService.txList(shouxufei, sn, from1.getId(), "14");
						}
					}

					price = CurrencyUtil.sub(price, jiaoyi);
					comMoneyAll = CurrencyUtil.add(comMoneyAll, shouxufei);
				} else if (i == ownerList.size() - 1) {
					// 最后一个金额一定富裕，不能扣除所有金额
					MemberWallet from2 = memberWalletService.getMemberWalletInfo(memberId, ownerList.get(i));
					Double shouxufei = 0D;// 手续费
					// 计算手续费
					if (StrUtil.equalsAny(ownerList.get(i), WalletOwnerEnum.SALE.name(), WalletOwnerEnum.PROMOTE.name(),
							WalletOwnerEnum.PROMOTE_FW.name(), WalletOwnerEnum.PROMOTE_HY.name())) {

						shouxufei = CurrencyUtil.mul(price,
								Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.ORDER_FEE.dictCode())));
						comMoneyAll = CurrencyUtil.add(comMoneyAll, shouxufei);

						MemberWallet adminp = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(), "平台");// 手续费
																													// ，平台推广钱包

						if (shouxufei > 0D) {
							String proxyUser = getProxy(from2.getMemberId());
							if (StringUtils.isNotEmpty(proxyUser)) {
								MemberWallet proxy = memberWalletService.getMemberWalletInfo(proxyUser,
										WalletOwnerEnum.PROMOTE_FW.name());// 代理商
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from2, proxy,
										CurrencyUtil.mul(shouxufei, apportionFee("城市合伙人")), "扫码付款手续费");// 手续费到代理商
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from2, adminp,
										CurrencyUtil.mul(shouxufei, apportionFee("平台")), "扫码付款手续费");// 手续费到平台
							} else {
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from2, adminp,
										shouxufei, "扫码付款手续费");// 手续费
							}
						}
					}
					walletUpdate(sn, DepositServiceTypeEnum.WALLET_PAY.name(), from2, to, price, "扫码付款");// 转账
					updateCombined(sn, ownerList.get(i), from2, price, shouxufei, 0D);
					// 推广钱包-会员费，支付扣款逻辑
					if (ownerList.get(i).equals(WalletOwnerEnum.PROMOTE_HY.name())) {
						rechargeFowService.updatePromote(sn, price, from2.getMemberId(), "22");
						if (shouxufei > 0D) {
							rechargeFowService.updatePromote(sn, shouxufei, from2.getMemberId(), "24");
						}
					}
					// 支出销售金额
					if (ownerList.get(i).equals(WalletOwnerEnum.SALE.name())) {
						memberWithdrawApplyService.txList(money, sn, from2.getId(), "12");
						if (shouxufei > 0D) {
							memberWithdrawApplyService.txList(shouxufei, sn, from2.getId(), "14");
						}
					}
				} else {
					// 扣除所有金额
					MemberWallet from3 = memberWalletService.getMemberWalletInfo(memberId, ownerList.get(i));
					Double memberWallet = memberWalletService.getMemberWallet(memberId, ownerList.get(i))
							.getMemberWallet();// 钱包余额
					Double jiaoyi = memberWallet;// 交易金额
					Double shouxufei = 0D;// 手续费
					// 计算手续费
					if (StrUtil.equalsAny(ownerList.get(i), WalletOwnerEnum.SALE.name(), WalletOwnerEnum.PROMOTE.name(),
							WalletOwnerEnum.PROMOTE_FW.name(), WalletOwnerEnum.PROMOTE_HY.name())) {
						Double fee = CurrencyUtil.add(
								Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.ORDER_FEE.dictCode())), 1D);// 手续费费率
						jiaoyi = CurrencyUtil.div(memberWallet, fee);// 交易金额
						shouxufei = CurrencyUtil.sub(memberWallet, jiaoyi);// 手续费
						MemberWallet adminp = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(), "平台");// 手续费
																													// ，平台推广钱包

						if (shouxufei > 0D) {
							String proxyUser = getProxy(from3.getMemberId());
							if (StringUtils.isNotEmpty(proxyUser)) {
								MemberWallet proxy = memberWalletService.getMemberWalletInfo(proxyUser,
										WalletOwnerEnum.PROMOTE_FW.name());// 代理商
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from3, proxy,
										CurrencyUtil.mul(shouxufei, apportionFee("城市合伙人")), "扫码付款手续费");// 手续费到代理商
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from3, adminp,
										CurrencyUtil.mul(shouxufei, apportionFee("平台")), "扫码付款手续费");// 手续费到平台
							} else {
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from3, adminp,
										shouxufei, "扫码付款手续费");// 手续费
							}
						}
						comMoneyAll = CurrencyUtil.add(comMoneyAll, shouxufei);
					}
					walletUpdate(sn, DepositServiceTypeEnum.WALLET_PAY.name(), from3, to, jiaoyi, "扫码付款");// 转账
					updateCombined(sn, ownerList.get(i), from3, jiaoyi, shouxufei, 0D);
					// 推广钱包-会员费，支付扣款逻辑
					if (ownerList.get(i).equals(WalletOwnerEnum.PROMOTE_HY.name())) {
						rechargeFowService.updatePromote(sn, jiaoyi, from3.getMemberId(), "22");
						if (shouxufei > 0D) {
							rechargeFowService.updatePromote(sn, shouxufei, from3.getMemberId(), "24");
						}
					}
					// 支出销售金额
					if (ownerList.get(i).equals(WalletOwnerEnum.SALE.name())) {
						memberWithdrawApplyService.txList(money, sn, from3.getId(), "12");
						if (shouxufei > 0D) {
							memberWithdrawApplyService.txList(shouxufei, sn, from3.getId(), "14");
						}
					}
					price = CurrencyUtil.sub(price, jiaoyi);
				}
			}
			order.setCommission(comMoneyAll);
			order.setFlowPrice(CurrencyUtil.add(order.getFlowPrice(), comMoneyAll));
			orderService.updateById(order);
			log.info("分佣 splitCommission---------------------------------------- start");
			CommissionData cd = new CommissionData(money, comMoneyAll);// 佣金计算
			// angelCommission(sn,from,to,money,comMoney,type,cd);//给天使分佣
			careerCommission(sn, from, to, money, comMoneyAll, "xf", cd);// 给事业分佣
			// dealerCommission(sn,from,to,money,comMoneyAll,"xf",cd);//给代理商分佣
			log.info("分佣 splitCommission---------------------------------------- end");

		}

		return true;
	}

	void updateCombined(String sn, String type, MemberWallet from, Double money, Double value, Double colMoney) {
		// money 订单金额
		// value 手续费
		// colMoney 运费
		log.info("扣款明细记录---------------------------------------- start");
		CombinedPayment combinedPayment = new CombinedPayment();
		combinedPayment.setSn(sn);
		combinedPayment.setMemberId(from.getMemberId());
		combinedPayment.setMoney(money);
		combinedPayment.setColMoney(colMoney);
		combinedPayment.setCommmissionMoney(value);
		combinedPayment.setWalletType(type);

		combinedPayment.setWalletMoney(CurrencyUtil.add(money, colMoney, value));

		combinedPaymentService.save(combinedPayment);
		log.info("扣款明细记录---------------------------------------- end");

	}

	/**
	 * 充值会员
	 *
	 * @param sn
	 *            交易流水
	 * @param from
	 *            转出钱包
	 * @param money
	 *            交易金额
	 * @return
	 */
	public boolean upgradHy(String sn, MemberWallet from, Double money) {
		MemberWallet admin = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_HY.name(), "平台"); // 平台余额

		if (money > 0D) {
			String proxyUser = getProxy(from.getMemberId());
			if (StringUtils.isNotEmpty(proxyUser)) {
				MemberWallet proxy = memberWalletService.getMemberWalletInfo(proxyUser,
						WalletOwnerEnum.PROMOTE_HY.name());// 代理商
				walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_HY.name(), from, proxy,
						CurrencyUtil.mul(money, apportionFee("城市合伙人")), "会员费");// 会员费到代理商
				walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_HY.name(), from, admin,
						CurrencyUtil.mul(money, apportionFee("平台")), "会员费");// 会员费到平台
			} else {
				walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_HY.name(), from, admin, money, "会员费");//
				// 会员费
			}
		}
		splitCommission(sn, from, admin, money, 0D, "hy");// 会员分佣
		return true;
	}

	/**
	 * 充值合伙人
	 *
	 * @param sn
	 *            交易流水
	 * @param from
	 *            转出钱包
	 * @param money
	 *            交易金额
	 * @return
	 */
	public boolean upgradHhr(String sn, MemberWallet from, Double money) {
		MemberWallet admin = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(), "平台"); // 平台余额
		walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_FW.name(), from, admin, money, "合伙人费");// A 到平台余额钱包
																											// 合伙人费
		// splitCommission(sn,from,admin,money,0D,"hhr");//合伙人分佣
		return true;
	}

	/**
	 * 用户 平台 交易佣金 手续费
	 *
	 * @param sn
	 *            交易流水
	 * @param from
	 *            转出钱包
	 * @param to
	 *            转入钱包
	 * @param money
	 *            交易金额
	 * @param comMoney
	 *            手续费
	 * @param type
	 *            交易类型 hy 会员,xf 消费
	 */
	@Transactional
	public void splitCommission(String sn, MemberWallet from, MemberWallet to, Double money, Double comMoney,
			String type) {
		log.info("分佣 splitCommission---------------------------------------- start");
		CommissionData cd = new CommissionData(money, comMoney);// 佣金计算
		angelCommission(sn, from, to, money, comMoney, type, cd);// 给天使分佣
		careerCommission(sn, from, to, money, comMoney, type, cd);// 给事业分佣
		// dealerCommission(sn,from,to,money,comMoney,type,cd);//给代理商分佣
		log.info("分佣 splitCommission---------------------------------------- end");
	}

	/**
	 * 用户 平台 交易佣金 手续费
	 *
	 * @param sn
	 *            交易流水
	 * @param from
	 *            转出钱包
	 * @param to
	 *            转入钱包
	 * @param money
	 *            交易金额
	 * @param comMoney
	 *            手续费
	 * @param type
	 *            交易类型 hy 会员,xf 消费
	 */
	@Transactional
	public void splitCommissionFrozen(String sn, MemberWallet from, MemberWallet to, Double money, Double comMoney,
			String type) {
		log.info("分佣冻结 splitCommissionFrozen---------------------------------------- start");
		CommissionData cd = new CommissionData(money, comMoney);// 佣金计算
		angelCommissionFrozen(sn, from, to, money, comMoney, type, cd);// 给天使分佣
		careerCommissionFrozen(sn, from, to, money, comMoney, type, cd);// 给事业分佣
		// dealerCommission(sn,from,to,money,comMoney,type,cd);//给代理商分佣
		log.info("分佣冻结 splitCommissionFrozen---------------------------------------- end");
	}

	/**
	 * 天使分佣
	 *
	 * @param sn
	 *            交易流水
	 * @param from
	 *            转出钱包
	 * @param to
	 *            转入钱包
	 * @param money
	 *            交易金额
	 * @param comMoney
	 *            手续费
	 * @param type
	 *            交易类型 hy 会员,xf 消费 //合伙人类型 0 非合伙人 1 事业合伙人 2 天使合伙人 3 推广员 4 城市代理商
	 * @return
	 */
	@Transactional
	public void angelCommission(String sn, MemberWallet from, MemberWallet to, Double money, Double comMoney,
			String type, CommissionData cd) {
		log.info("天使分佣 angelCommission---------------------------------------- start");
		Member member = getExtMember(from.getMemberId());

		String proxyUser = getProxy(from.getMemberId());// 获取代理商
		MemberWallet proxy = memberWalletService.getMemberWalletInfo(proxyUser, WalletOwnerEnum.PROMOTE_FW.name());// 代理商
		if (ObjectUtil.isNotNull(member)) {// 获取推广人
			Integer memberType = getMemberType(member.getId());
			if (ObjectUtil.isNotNull(memberType) && memberType == 2) {// 天使合伙人
				if (StrUtil.equals("hy", type)) {// 充值会员
					proxy = memberWalletService.getMemberWalletInfo(proxyUser, WalletOwnerEnum.PROMOTE_HY.name());// 代理商
					MemberWallet admin = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_HY.name(), "平台");
					MemberWallet tshhr = getMemberWalletInfo(member.getId(), WalletOwnerEnum.PROMOTE.name());
					Double val = CurrencyUtil.mul(money, Double
							.valueOf(SysDictUtils.getValueString(DictCodeEnum.MEMBERSHIP_RATE.dictCode(), "天使合伙人")), 5);
					log.info("用户: {} 佣金费用{} 费率{}", tshhr.getMemberId(), val, Double
							.valueOf(SysDictUtils.getValueString(DictCodeEnum.MEMBERSHIP_RATE.dictCode(), "天使合伙人")));

					if (val > 0D) {
						if (StringUtils.isNotEmpty(proxyUser)) {
							walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_HY.name(), proxy, tshhr,
									CurrencyUtil.mul(val, apportionFee("城市合伙人")), "会员费佣金");// 会员费佣金到代理商
							walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_HY.name(), admin, tshhr,
									CurrencyUtil.mul(val, apportionFee("平台")), "会员费佣金");// 会员费佣金到平台
							rechargeFowService.updatePromote(sn, CurrencyUtil.mul(val, apportionFee("城市合伙人")),
									proxy.getMemberId(), "25");
							rechargeFowService.updatePromote(sn, CurrencyUtil.mul(val, apportionFee("平台")),
									admin.getMemberId(), "25");
						} else {
							walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_HY.name(), admin, tshhr, val,
									"会员费佣金");// 会员费佣金
							rechargeFowService.updatePromote(sn, CurrencyUtil.mul(val, apportionFee("平台")),
									admin.getMemberId(), "25");
						}
					}
					cd.deductMoney(val);
				}
				if (StrUtil.equals("xf", type)) {
					QueryWrapper<Partner> queryWrapper = new QueryWrapper<>();
					queryWrapper.eq("member_id", from.getMemberId());
					queryWrapper.eq("partner_state", 0);
					queryWrapper.orderByDesc("end_time");
					queryWrapper.last("limit 1");
					Partner partner = partnerMapper.selectOne(queryWrapper);

					if (StrUtil.equalsAny(from.getOwner(), WalletOwnerEnum.RECHARGE.name()) && partner == null) {// 充值钱包消费
						MemberWallet admin = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(), "平台");
						MemberWallet tshhr = getMemberWalletInfo(member.getId(), WalletOwnerEnum.PROMOTE.name());
						Double val = CurrencyUtil.mul(money,
								Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "天使合伙人")),
								5);
						log.info("当前用户: {} 佣金费用 {} 费率{}", tshhr.getMemberId(), val, Double
								.valueOf(SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "天使合伙人")));

						if (val > 0D) {
							if (StringUtils.isNotEmpty(proxyUser)) {
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_TS.name(), proxy, tshhr,
										CurrencyUtil.mul(val, apportionFee("城市合伙人")), "消费佣金");// 消费佣金
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_TS.name(), admin, tshhr,
										CurrencyUtil.mul(val, apportionFee("平台")), "消费佣金");// 消费佣金
								rechargeFowService.updatePromote(sn, CurrencyUtil.mul(val, apportionFee("城市合伙人")),
										proxy.getMemberId(), "25");
							} else {
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_TS.name(), admin, tshhr, val,
										"消费佣金");// 消费佣金
							}
						}
						cd.deductMoney(val);
					}

				}

			}

		}
		log.info("天使分佣 angelCommission---------------------------------------- end");
	}

	/**
	 * 天使分佣冻结
	 *
	 * @param sn
	 *            交易流水
	 * @param from
	 *            转出钱包
	 * @param to
	 *            转入钱包
	 * @param money
	 *            交易金额
	 * @param comMoney
	 *            手续费
	 * @param type
	 *            交易类型 hy 会员,xf 消费 //合伙人类型 0 非合伙人 1 事业合伙人 2 天使合伙人 3 推广员 4 城市代理商
	 * @return
	 */
	@Transactional
	public void angelCommissionFrozen(String sn, MemberWallet from, MemberWallet to, Double money, Double comMoney,
			String type, CommissionData cd) {
		log.info("天使分佣冻结 angelCommissionFrozen---------------------------------------- start");
		Member member = getExtMember(from.getMemberId());

		String proxyUser = getProxy(from.getMemberId());// 获取代理商
		MemberWallet proxy = memberWalletService.getMemberWalletInfo(proxyUser, WalletOwnerEnum.PROMOTE_FW.name());// 代理商
		if (ObjectUtil.isNotNull(member)) {// 获取推广人
			Integer memberType = getMemberType(member.getId());
			if (ObjectUtil.isNotNull(memberType) && memberType == 2) {// 天使合伙人
				if (StrUtil.equals("hy", type)) {// 充值会员
					proxy = memberWalletService.getMemberWalletInfo(proxyUser, WalletOwnerEnum.PROMOTE_HY.name());// 代理商
					MemberWallet admin = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_HY.name(), "平台");
					MemberWallet tshhr = getMemberWalletInfo(member.getId(), WalletOwnerEnum.PROMOTE.name());
					Double val = CurrencyUtil.mul(money, Double
							.valueOf(SysDictUtils.getValueString(DictCodeEnum.MEMBERSHIP_RATE.dictCode(), "天使合伙人")), 5);
					log.info("用户: {} 佣金费用{} 费率{}", tshhr.getMemberId(), val, Double
							.valueOf(SysDictUtils.getValueString(DictCodeEnum.MEMBERSHIP_RATE.dictCode(), "天使合伙人")));

					if (val > 0D) {
						if (StringUtils.isNotEmpty(proxyUser)) {
							walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_HY.name(), proxy, tshhr,
									CurrencyUtil.mul(val, apportionFee("城市合伙人")), "会员费佣金");// 会员费佣金到代理商
							walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_HY.name(), admin, tshhr,
									CurrencyUtil.mul(val, apportionFee("平台")), "会员费佣金");// 会员费佣金到平台
							// walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_HY.name(), proxy,
							// tshhr,
							// CurrencyUtil.mul(val, apportionFee("城市合伙人")), "会员费佣金");// 会员费佣金到代理商
							// walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_HY.name(), admin,
							// tshhr,
							// CurrencyUtil.mul(val, apportionFee("平台")), "会员费佣金");// 会员费佣金到平台
							// rechargeFowService.updatePromote(sn, CurrencyUtil.mul(val,
							// apportionFee("城市合伙人")),
							// proxy.getMemberId(), "25");
							// rechargeFowService.updatePromote(sn, CurrencyUtil.mul(val,
							// apportionFee("平台")),
							// admin.getMemberId(), "25");
						} else {
							walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_HY.name(), admin, tshhr, val,
									"会员费佣金");// 会员费佣金
							// walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_HY.name(), admin,
							// tshhr, val,
							// "会员费佣金");// 会员费佣金
							// rechargeFowService.updatePromote(sn, CurrencyUtil.mul(val,
							// apportionFee("平台")),
							// admin.getMemberId(), "25");
						}
					}
					cd.deductMoney(val);
				}
				if (StrUtil.equals("xf", type)) {
					QueryWrapper<Partner> queryWrapper = new QueryWrapper<>();
					queryWrapper.eq("member_id", from.getMemberId());
					queryWrapper.eq("partner_state", 0);
					queryWrapper.orderByDesc("end_time");
					queryWrapper.last("limit 1");
					Partner partner = partnerMapper.selectOne(queryWrapper);

					if (StrUtil.equalsAny(from.getOwner(), WalletOwnerEnum.RECHARGE.name()) && partner == null) {// 充值钱包消费
						MemberWallet admin = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(), "平台");
						MemberWallet tshhr = getMemberWalletInfo(member.getId(), WalletOwnerEnum.PROMOTE.name());
						Double val = CurrencyUtil.mul(money,
								Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "天使合伙人")),
								5);
						log.info("当前用户: {} 佣金费用 {} 费率{}", tshhr.getMemberId(), val, Double
								.valueOf(SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "天使合伙人")));

						if (val > 0D) {
							if (StringUtils.isNotEmpty(proxyUser)) {
								walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_TS.name(), proxy, tshhr,
										CurrencyUtil.mul(val, apportionFee("城市合伙人")), "消费佣金");// 消费佣金
								walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_TS.name(), admin, tshhr,
										CurrencyUtil.mul(val, apportionFee("平台")), "消费佣金");// 消费佣金
								// walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_TS.name(), proxy,
								// tshhr,
								// CurrencyUtil.mul(val, apportionFee("城市合伙人")), "消费佣金");// 消费佣金
								// walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_TS.name(), admin,
								// tshhr,
								// CurrencyUtil.mul(val, apportionFee("平台")), "消费佣金");// 消费佣金
								// rechargeFowService.updatePromote(sn, CurrencyUtil.mul(val,
								// apportionFee("城市合伙人")),
								// proxy.getMemberId(), "25");
							} else {
								walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_TS.name(), admin, tshhr,
										val, "消费佣金");// 消费佣金
								// walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_TS.name(), admin,
								// tshhr,
								// val,
								// "消费佣金");// 消费佣金
							}
						}
						cd.deductMoney(val);
					}

				}

			}

		}
		log.info("天使分佣冻结 angelCommissionFrozen---------------------------------------- end");
	}

	/**
	 * 事业分佣
	 *
	 * @param money
	 *            消费金额
	 * @param type
	 *            消费类型
	 * @return
	 */
	@Transactional
	public void careerCommission(String sn, MemberWallet from, MemberWallet to, Double money, Double comMoney,
			String type, CommissionData cd) {
		log.info("事业分佣 careerCommission---------------------------------------- start");
		Member member = getExtMember(to.getMemberId());
		String proxyUser = getProxy(from.getMemberId());// 获取代理商
		MemberWallet proxy = memberWalletService.getMemberWalletInfo(proxyUser, WalletOwnerEnum.PROMOTE_FW.name());// 代理商
		if (ObjectUtil.isNotNull(member)) {// 获取推广人
			Integer memberType = getMemberType(member.getId());
			if (ObjectUtil.isNotNull(memberType) && memberType == 1) {// 事业合伙人
				if (StrUtil.equals("xf", type)) {
					if (StrUtil.equalsAny(from.getOwner(), WalletOwnerEnum.RECHARGE.name())) {// 充值钱包消费
						MemberWallet admin = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(), "平台");
						MemberWallet syhhr = getMemberWalletInfo(member.getId(), WalletOwnerEnum.PROMOTE.name());
						Double val = CurrencyUtil.mul(money,
								Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "事业合伙人")),
								5);
						log.info("当前用户: {} 佣金费用 {} 费率{}", syhhr.getMemberId(), val, Double
								.valueOf(SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "事业合伙人")));

						if (val > 0D) {
							if (StringUtils.isNotEmpty(proxyUser)) {
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), proxy, syhhr,
										CurrencyUtil.mul(val, apportionFee("城市合伙人")), "消费佣金");// 消费佣金
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), admin, syhhr,
										CurrencyUtil.mul(val, apportionFee("平台")), "消费佣金");// 消费佣金
								rechargeFowService.updatePromote(sn, CurrencyUtil.mul(val, apportionFee("城市合伙人")),
										proxy.getMemberId(), "25");

							} else {
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), admin, syhhr, val,
										"消费佣金");// 消费佣金
							}
						}
						cd.deductMoney(val);// 累计分佣金额
					}
					if (StrUtil.equalsAny(from.getOwner(), WalletOwnerEnum.SALE.name(), WalletOwnerEnum.PROMOTE.name(),
							WalletOwnerEnum.PROMOTE_HY.name(), WalletOwnerEnum.PROMOTE_FW.name())) { // 销售 推广 钱包消费
						MemberWallet admin = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(), "平台");
						MemberWallet syhhr = getMemberWalletInfo(member.getId(), WalletOwnerEnum.PROMOTE.name());
						Double val = CurrencyUtil.mul(money,
								Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "事业合伙人")),
								5);
						log.info("当前用户: {} 佣金费用 {} 费率{}", syhhr.getMemberId(), val, Double
								.valueOf(SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "事业合伙人")));

						if (val > 0D) {
							if (StringUtils.isNotEmpty(proxyUser)) {
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), proxy, syhhr,
										CurrencyUtil.mul(val, apportionFee("城市合伙人")), "消费佣金");// 消费佣金
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), admin, syhhr,
										CurrencyUtil.mul(val, apportionFee("平台")), "消费佣金");// 消费佣金
								rechargeFowService.updatePromote(sn, CurrencyUtil.mul(val, apportionFee("城市合伙人")),
										proxy.getMemberId(), "25");
							} else {
								walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), admin, syhhr, val,
										"消费佣金");// 消费佣金
							}
						}
						cd.deductcomMoney(val);// 累计手续费分佣金额
					}
				}
			}
		}
		log.info("事业分佣 careerCommission---------------------------------------- end");
	}

	/**
	 * 事业分佣冻结
	 *
	 * @param money
	 *            消费金额
	 * @param type
	 *            消费类型
	 * @return
	 */
	@Transactional
	public void careerCommissionFrozen(String sn, MemberWallet from, MemberWallet to, Double money, Double comMoney,
			String type, CommissionData cd) {
		log.info("事业分佣冻结 careerCommissionFrozen---------------------------------------- start");
		Member member = getExtMember(to.getMemberId());
		String proxyUser = getProxy(from.getMemberId());// 获取代理商
		MemberWallet proxy = memberWalletService.getMemberWalletInfo(proxyUser, WalletOwnerEnum.PROMOTE_FW.name());// 代理商
		if (ObjectUtil.isNotNull(member)) {// 获取推广人
			Integer memberType = getMemberType(member.getId());
			if (ObjectUtil.isNotNull(memberType) && memberType == 1) {// 事业合伙人
				if (StrUtil.equals("xf", type)) {
					if (StrUtil.equalsAny(from.getOwner(), WalletOwnerEnum.RECHARGE.name())) {// 充值钱包消费
						MemberWallet admin = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(), "平台");
						MemberWallet syhhr = getMemberWalletInfo(member.getId(), WalletOwnerEnum.PROMOTE.name());
						Double val = CurrencyUtil.mul(money,
								Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "事业合伙人")),
								5);
						log.info("当前用户: {} 佣金费用 {} 费率{}", syhhr.getMemberId(), val, Double
								.valueOf(SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "事业合伙人")));

						if (val > 0D) {
							if (StringUtils.isNotEmpty(proxyUser)) {
								walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), proxy, syhhr,
										CurrencyUtil.mul(val, apportionFee("城市合伙人")), "消费佣金");// 消费佣金
								walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), admin, syhhr,
										CurrencyUtil.mul(val, apportionFee("平台")), "消费佣金");// 消费佣金
								// walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), proxy,
								// syhhr,
								// CurrencyUtil.mul(val, apportionFee("城市合伙人")), "消费佣金");// 消费佣金
								// walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), admin,
								// syhhr,
								// CurrencyUtil.mul(val, apportionFee("平台")), "消费佣金");// 消费佣金
								// rechargeFowService.updatePromote(sn, CurrencyUtil.mul(val,
								// apportionFee("城市合伙人")),
								// proxy.getMemberId(), "25");

							} else {
								walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), admin, syhhr,
										val, "消费佣金");// 消费佣金
								// walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), admin,
								// syhhr,
								// val,
								// "消费佣金");// 消费佣金
							}
						}
						cd.deductMoney(val);// 累计分佣金额
					}
					if (StrUtil.equalsAny(from.getOwner(), WalletOwnerEnum.SALE.name(), WalletOwnerEnum.PROMOTE.name(),
							WalletOwnerEnum.PROMOTE_HY.name(), WalletOwnerEnum.PROMOTE_FW.name())) { // 销售 推广 钱包消费
						MemberWallet admin = getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(), "平台");
						MemberWallet syhhr = getMemberWalletInfo(member.getId(), WalletOwnerEnum.PROMOTE.name());
						Double val = CurrencyUtil.mul(money,
								Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "事业合伙人")),
								5);
						log.info("当前用户: {} 佣金费用 {} 费率{}", syhhr.getMemberId(), val, Double
								.valueOf(SysDictUtils.getValueString(DictCodeEnum.FLOW_RATE.dictCode(), "事业合伙人")));

						if (val > 0D) {
							if (StringUtils.isNotEmpty(proxyUser)) {
								walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), proxy, syhhr,
										CurrencyUtil.mul(val, apportionFee("城市合伙人")), "消费佣金");// 消费佣金
								walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), admin, syhhr,
										CurrencyUtil.mul(val, apportionFee("平台")), "消费佣金");// 消费佣金
								// walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), proxy,
								// syhhr,
								// CurrencyUtil.mul(val, apportionFee("城市合伙人")), "消费佣金");// 消费佣金
								// walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), admin,
								// syhhr,
								// CurrencyUtil.mul(val, apportionFee("平台")), "消费佣金");// 消费佣金
								// rechargeFowService.updatePromote(sn, CurrencyUtil.mul(val,
								// apportionFee("城市合伙人")),
								// proxy.getMemberId(), "25");
							} else {
								walletFrozenIn(sn, DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), admin, syhhr,
										val, "消费佣金");// 消费佣金
								// walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_SY.name(), admin,
								// syhhr,
								// val,
								// "消费佣金");// 消费佣金
							}
						}
						cd.deductcomMoney(val);// 累计手续费分佣金额
					}
				}
			}
		}
		log.info("事业分佣冻结 careerCommissionFrozen---------------------------------------- end");
	}

	/**
	 * 代理商分佣
	 * 
	 * @param money
	 *            消费金额
	 * @param type
	 *            消费类型
	 * @param comMoney
	 *            消费类型
	 * @return
	 */
	// @Transactional
	// public void dealerCommission(String sn, MemberWallet from, MemberWallet to,
	// Double money, Double comMoney, String
	// type, CommissionData cd) {
	// log.info("代理商分佣 dealerCommission----------------------------------------
	// start");
	// String proxyUser = getProxy(from.getMemberId());
	// if (StringUtils.isNotEmpty(proxyUser)) {
	// if (StrUtil.equals("hy", type)) {//c端充值会员
	// MemberWallet admin = getMemberWalletInfo("admin",
	// WalletOwnerEnum.PROMOTE.name(), "平台");
	// MemberWallet proxy = memberWalletService.getMemberWalletInfo(proxyUser,
	// WalletOwnerEnum.PROMOTE_FW.name());//代理商
	// Double val = CurrencyUtil.mul(money - cd.getDeductMoney(),
	// Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.APPORTION_FEE.dictCode(),"城市合伙人")),
	// 5);
	// log.info("当前用户: {} 佣金费用 {} 费率{}", proxy.getMemberId(), val,
	// Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.APPORTION_FEE.dictCode(),"城市合伙人")));
	// walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION_HY.name(), admin,
	// proxy, val,"佣金");//平台到代理商 佣金
	// cd.deductMoney(val);//累计分佣金额
	// }
	// if (StrUtil.equals("xf", type)) {
	// if (StrUtil.equalsAny(from.getOwner(), WalletOwnerEnum.RECHARGE.name()))
	// {//充值 消费
	// MemberWallet admin = getMemberWalletInfo("admin",
	// WalletOwnerEnum.PROMOTE.name(), "平台");
	// MemberWallet proxy = memberWalletService.getMemberWalletInfo(proxyUser,
	// WalletOwnerEnum.PROMOTE_FW.name());//代理商
	// Double val = CurrencyUtil.mul(cd.getDeductMoney(),
	// Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.APPORTION_FEE.dictCode(),"城市合伙人")),
	// 5);
	// log.info("当前用户: {} 与平台平摊佣金费用 {} 费率{}", proxy.getMemberId(), val,
	// Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.APPORTION_FEE.dictCode(),"城市合伙人")));
	// walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION.name(), proxy,
	// admin, val,"平摊佣金");//代理商到平台 平摊佣金
	// }
	// if (StrUtil.equalsAny(from.getOwner(), WalletOwnerEnum.SALE.name(),
	// WalletOwnerEnum.PROMOTE.name(),
	// WalletOwnerEnum.PROMOTE_HY.name(), WalletOwnerEnum.PROMOTE_FW.name())) {//销售
	// 推广 消费
	// MemberWallet admin = getMemberWalletInfo("admin",
	// WalletOwnerEnum.PROMOTE.name(), "平台");
	// MemberWallet proxy = memberWalletService.getMemberWalletInfo(proxyUser,
	// WalletOwnerEnum.PROMOTE_FW.name());//代理商
	// Double val = CurrencyUtil.mul(comMoney - cd.getDeductcomMoney(),
	// Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.APPORTION_FEE.dictCode(),"城市合伙人")),
	// 5);
	// log.info("当前用户: {} 佣金费用 {} 费率{}", proxy.getMemberId(), val,
	// Double.valueOf(SysDictUtils.getValueString(DictCodeEnum.APPORTION_FEE.dictCode(),"城市合伙人")));
	// walletUpdate(sn, DepositServiceTypeEnum.WALLET_COMMISSION.name(), admin,
	// proxy, val,"佣金");//平台到代理商 佣金
	// }
	//
	// }
	//
	// }
	// log.info("代理商分佣 dealerCommission----------------------------------------
	// end");
	// }

	/**
	 * @param sn
	 *            交易流水号
	 * @param type
	 *            交易类型 0 余额充值 1消费 2佣金 3销售 4年费充值 5合伙人充值 6 提现 7 退款 8 退佣金 9 商家提现
	 * @param from
	 *            来源用户
	 * @param to
	 *            去向用户
	 * @param value
	 *            金额
	 */
	@Transactional
	public boolean walletUpdate(String sn, String type, MemberWallet from, MemberWallet to, Double value,
			String remark) {

		log.info("来源用户钱包 {}", JSONUtil.toJsonStr(from));
		log.info("目标用户钱包 {}", JSONUtil.toJsonStr(to));

		WalletDetail detail = new WalletDetail();
		detail.setSn(sn);
		detail.setTransactionType(type);
		if(from != null){
			detail.setPayer(from.getMemberId());
			detail.setPayerName(from.getMemberName());
			detail.setPayerOwner(from.getOwner());
			detail.setPayerBeforeMoney(from.getMemberWallet());

			from.setMemberWallet(CurrencyUtil.sub(from.getMemberWallet(), value));
			this.baseMapper.update(from,
				new QueryWrapper<MemberWallet>().eq("id", from.getId()).eq("owner", from.getOwner()));
			detail.setPayerAfterMoney(from.getMemberWallet());

			log.info("来源用户 变更后 {}", JSONUtil.toJsonStr(from));
		}
		if(to != null){
			detail.setPayee(to.getMemberId());
			detail.setPayeeName(to.getMemberName());
			detail.setPayeeOwner(to.getOwner());
			detail.setPayeeBeforeMoney(to.getMemberWallet());

			to.setMemberWallet(CurrencyUtil.add(to.getMemberWallet(), value));
			this.baseMapper.update(to, new QueryWrapper<MemberWallet>().eq("id", to.getId()).eq("owner", to.getOwner()));
			detail.setPayeeAfterMoney(to.getMemberWallet());

			log.info("目标用户 变更后 {}", JSONUtil.toJsonStr(to));
		}

		detail.setMoney(value);
		detail.setRemark(remark);

		walletDetailService.save(detail);
		log.info("目标用户 变更记录 {}", JSONUtil.toJsonStr(detail));

		log.info("钱包交易完毕 ");
		return true;

	}

	/**
	 * 冻结钱包入账
	 * 
	 * @param sn
	 *            交易流水号
	 * @param type
	 *            交易类型 0 余额充值 1消费 2佣金 3销售 4年费充值 5合伙人充值 6 提现 7 退款 8 退佣金 9 商家提现
	 * @param from
	 *            来源用户
	 * @param to
	 *            去向用户
	 * @param value
	 *            金额
	 */
	@Transactional
	public boolean walletFrozenIn(String sn, String type, MemberWallet from, MemberWallet to, Double value,
			String remark) {

		log.info("来源用户钱包 {}", JSONUtil.toJsonStr(from));
		log.info("目标用户钱包 {}", JSONUtil.toJsonStr(to));

		WalletFrozenDetail detail = new WalletFrozenDetail();
		detail.setSn(sn);
		detail.setTransactionType(type);
		detail.setPayer(from.getMemberId());
		detail.setPayerName(from.getMemberName());
		detail.setPayerOwner(from.getOwner());
		detail.setPayerBeforeMoney(from.getMemberWallet());

		detail.setPayee(to.getMemberId());
		detail.setPayeeName(to.getMemberName());
		detail.setPayeeOwner(to.getOwner());
		detail.setPayeeBeforeMoney(to.getMemberFrozenWallet());

		detail.setMoney(value);
		detail.setRemark(remark);

		from.setMemberWallet(CurrencyUtil.sub(from.getMemberWallet() != null ? from.getMemberWallet() : 0D, value));
		this.baseMapper.update(from,
				new QueryWrapper<MemberWallet>().eq("id", from.getId()).eq("owner", from.getOwner()));
		detail.setPayerAfterMoney(from.getMemberWallet());

		log.info("来源用户 变更后 {}", JSONUtil.toJsonStr(from));

		to.setMemberFrozenWallet(
				CurrencyUtil.add(to.getMemberFrozenWallet() != null ? to.getMemberFrozenWallet() : 0D, value));
		this.baseMapper.update(to, new QueryWrapper<MemberWallet>().eq("id", to.getId()).eq("owner", to.getOwner()));
		detail.setPayeeAfterMoney(to.getMemberFrozenWallet());

		log.info("目标用户 变更后 {}", JSONUtil.toJsonStr(to));

		detail.setCommissionFlag("0");
		walletFrozenDetailService.save(detail);
		log.info("目标用户 变更记录 {}", JSONUtil.toJsonStr(detail));

		log.info("钱包交易完毕 ");
		return true;

	}

	/**
	 * 冻结钱包出账
	 * 
	 * @param sn
	 *            交易流水号
	 * @param type
	 *            交易类型 0 余额充值 1消费 2佣金 3销售 4年费充值 5合伙人充值 6 提现 7 退款 8 退佣金 9 商家提现
	 * @param from
	 *            来源用户
	 * @param to
	 *            去向用户
	 * @param value
	 *            金额
	 */
	@Transactional
	public WalletFrozenDetail walletFrozenOut(String sn, String type, MemberWallet from, MemberWallet to, Double value,
			String remark) {

		log.info("来源用户钱包 {}", JSONUtil.toJsonStr(from));
		log.info("目标用户钱包 {}", JSONUtil.toJsonStr(to));

		WalletFrozenDetail detail = new WalletFrozenDetail();
		detail.setSn(sn);
		detail.setTransactionType(type);
		detail.setPayer(from.getMemberId());
		detail.setPayerName(from.getMemberName());
		detail.setPayerOwner(from.getOwner());
		detail.setPayerBeforeMoney(from.getMemberFrozenWallet());

		detail.setPayee(to.getMemberId());
		detail.setPayeeName(to.getMemberName());
		detail.setPayeeOwner(to.getOwner());
		detail.setPayeeBeforeMoney(to.getMemberWallet());

		detail.setMoney(value);
		detail.setRemark(remark);

		from.setMemberFrozenWallet(
				CurrencyUtil.sub(from.getMemberFrozenWallet() != null ? from.getMemberFrozenWallet() : 0D, value));
		this.baseMapper.update(from,
				new QueryWrapper<MemberWallet>().eq("id", from.getId()).eq("owner", from.getOwner()));
		detail.setPayerAfterMoney(from.getMemberFrozenWallet());

		log.info("来源用户 变更后 {}", JSONUtil.toJsonStr(from));

		to.setMemberWallet(CurrencyUtil.add(to.getMemberWallet() != null ? to.getMemberWallet() : 0D, value));
		this.baseMapper.update(to, new QueryWrapper<MemberWallet>().eq("id", to.getId()).eq("owner", to.getOwner()));
		detail.setPayeeAfterMoney(to.getMemberWallet());

		log.info("目标用户 变更后 {}", JSONUtil.toJsonStr(to));

		detail.setCommissionFlag("0");
		walletFrozenDetailService.save(detail);
		log.info("目标用户 变更记录 {}", JSONUtil.toJsonStr(detail));

		log.info("钱包交易完毕 ");
		return detail;

	}

	/**
	 * 获取用户钱包，当钱包不存在 ，创建一下新的钱包
	 *
	 * @param memberId
	 * @param owner
	 *            钱包类型 RECHARGE 余额， PROMOTE 推广， SALE 销售
	 * @return
	 */
	public MemberWallet getMemberWalletInfo(String memberId, String owner) {
		Member member = memberService.getById(memberId);

		if (member != null) {
			return getMemberWalletInfo(memberId, owner, member.getUsername());
		}
		return getMemberWalletInfo(memberId, owner, "");
	}

	/**
	 * 获取用户钱包，当钱包不存在 ，创建一下新的钱包
	 *
	 * @param memberId
	 * @param owner
	 * @return
	 */
	public MemberWallet getMemberWalletInfo(String memberId, String owner, String defultMemberName) {
		QueryWrapper<MemberWallet> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("member_id", memberId);
		queryWrapper.eq("owner", owner);
		queryWrapper.last("limit 1");
		MemberWallet mw = getOne(queryWrapper);
		if (ObjectUtil.isNull(mw)) {
			mw = new MemberWallet();
			mw.setMemberId(memberId);
			mw.setMemberName(defultMemberName);
			mw.setMemberWallet(0D);
			mw.setOwner(owner);
			save(mw);
			log.info("用户{}钱包不存在,创建新钱包 {}", memberId, JSONUtil.toJsonStr(mw));
		}
		log.info("获取用户{}-{}钱包 {}", memberId, owner, "钱包类型 RECHARGE 余额， PROMOTE 推广， SALE 销售");
		return mw;
	}

	/**
	 * 获取当前用户类型
	 *
	 * @param memberId
	 * @return
	 */
	public Integer getMemberType(String memberId) {
		QueryWrapper<Partner> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("member_id", memberId);
		queryWrapper.eq("partner_state", "0");
		queryWrapper.eq("delete_flag", "0");
		queryWrapper.last("limit 1");
		Partner partner = partnerService.getOne(queryWrapper);
		if (ObjectUtil.isNotNull(partner)) {
			log.info("用户{} ,类型为{} |0 非合伙人  1 事业合伙人  2 天使合伙人  3 推广员 4 城市代理商|", memberId, partner.getPartnerType());
			return partner.getPartnerType();
		}
		return null;
	}

	@Autowired
	private EextensionService eextensionService;

	/**
	 * 获取当前用户的推广人
	 *
	 * @param memberId
	 * @return
	 */
	public Member getExtMember(String memberId) {
		QueryWrapper<Extension> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("member_id", memberId);
		queryWrapper.eq("delete_flag", 0);
		queryWrapper.last("limit 1");
		Extension extension = eextensionService.getOne(queryWrapper);
		if (ObjectUtil.isNotNull(extension)) {
			QueryWrapper<Member> queryWrapper1 = new QueryWrapper();
			queryWrapper1.eq("promotion_code", extension.getExtension());
			queryWrapper1.eq("delete_flag", "0");
			queryWrapper1.last("limit 1");
			Member member = memberService.getOne(queryWrapper1);
			if (ObjectUtil.isNotNull(member)) {
				log.info("用户{}绑定的推广码{},推广人为{}", memberId, extension.getExtension(), member.getId());
				return member;
			}

		}
		return null;
	}

	/**
	 * 获取区域代理商
	 *
	 * @param memberId
	 * @return
	 */
	public String getProxy(String memberId) {
		Member member = memberService.getById(memberId);
		if (ObjectUtil.isNotNull(member) && StrUtil.isNotEmpty(member.getLocation())) {
			String code = member.getLocation();
			String province = StrUtil.concat(true, StrUtil.subPre(code, 2), "0000");
			String city = StrUtil.concat(true, StrUtil.subPre(code, 4), "00");

			QueryWrapper<Partner> wrapper = new QueryWrapper<>();
			wrapper.eq("partner_type", "4");// 代理商
			wrapper.eq("delete_flag", 0);
			wrapper.eq("audit_state", "PASS");
			wrapper.in("region_id", province, city, code);
			wrapper.orderByDesc("region_id");
			wrapper.last("limit 1");
			Partner one = partnerService.getOne(wrapper);
			if (null != one) {
				return one.getMemberId();
			}
		}
		return null;
	}

	/**
	 * cloFlag 包含运费，cloFlag true 包含，false 不包含
	 *
	 * @param sn
	 * @param colFlag
	 * @return
	 */
	public List<WalletDetail> getWalletLogDetail(String sn, boolean colFlag) {
		QueryWrapper<WalletDetail> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("sn", sn);
		if (!colFlag) {
			// 是否保护运费
			queryWrapper.notIn("transaction_type", DepositServiceTypeEnum.WALLET_COLLECT.name());
		}
		return walletDetailService.list(queryWrapper);
	}

	/**
	 *
	 * @param sn
	 * @return
	 */
	public List<WalletFrozenDetail> getWalletFrozenDetail(String sn) {
		List<WalletFrozenDetail> list = new ArrayList<>();
		QueryWrapper<WalletFrozenDetail> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("sn", sn);
		queryWrapper.notLike("transaction_type", "_REFUND");
		// 分佣
		List<WalletFrozenDetail> list1 = walletFrozenDetailService.list(queryWrapper);
		queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("sn", sn);
		queryWrapper.like("transaction_type", "_REFUND");
		// 退分佣
		List<WalletFrozenDetail> list2 = walletFrozenDetailService.list(queryWrapper);

		if (CollectionUtils.isNotEmpty(list1)) {
			if (CollectionUtils.isNotEmpty(list2)) {
				// 有退款
				for (WalletFrozenDetail walletFrozenDetail1 : list1) {
					for (WalletFrozenDetail walletFrozenDetail2 : list2) {
						if (walletFrozenDetail1.getPayer().equals(walletFrozenDetail2.getPayee())
								&& walletFrozenDetail2.getPayer().equals(walletFrozenDetail1.getPayee())) {
							Double sub = CurrencyUtil.sub(walletFrozenDetail1.getMoney(),
									walletFrozenDetail2.getMoney());
							if (sub.compareTo(0D) > 0) {
								// 钱没退完，还需要分佣
								WalletFrozenDetail wallet = walletFrozenDetail1;
								wallet.setPayerAfterMoney(CurrencyUtil.sub(wallet.getPayerBeforeMoney(), sub));
								wallet.setPayeeAfterMoney(CurrencyUtil.add(wallet.getPayeeBeforeMoney(), sub));
								wallet.setMoney(sub);
								list.add(wallet);
							}
						}
					}
				}
			} else {
				// 没有退款
				list.addAll(list1);
			}
		}
		return list;
	}

}
